1034. Head of a Gang (30)

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int tree[2010], sum[2010], smallindex[2010], bigindex[27000], weight[2010], cur, total[2010], headindex[2010];

int getbigindex(char s[])
{
	return (s[0] - 'A' + 1) * 27 * 27 + (s[1] - 'A' + 1) * 27 + s[2] - 'A' + 1;
}

int cmp(int a, int b)
{
	return smallindex[headindex[a]] < smallindex[headindex[b]];
}

void print(int index)
{
	int cur = smallindex[headindex[index]];
	int num[3];

	num[0] = cur / (27 * 27);
	num[1] = (cur - num[0] * 27 * 27) / 27;
	num[2] = cur % 27;

	int i;
	for(i = 0; i <= 2; i++)
	{
		printf("%c", num[i] + 'A' - 1);
	}

	printf(" %d\n", sum[index]);
}

int findroot(int root)
{
	if(tree[root] == -1)
	{
		return root;
	}
	else
	{
		tree[root] = findroot(tree[root]);
		return tree[root];
	}
}

void buildrelation(char s[2][5], int time)
{
	int index[2], i, curbigindex, cursmallindex;
	for(i = 0; i <= 1; i++)
	{
		curbigindex = getbigindex(s[i]);
		cursmallindex = bigindex[curbigindex];

		if(cursmallindex == 0)
		{
			index[i] = cursmallindex = ++cur;

			smallindex[cursmallindex] = curbigindex;
			bigindex[curbigindex] = cursmallindex;

			sum[cursmallindex] = 1;
			tree[cursmallindex] = -1;
		}
		else
		{
			index[i] = findroot(cursmallindex);
		}

		weight[cursmallindex] += time;
	}

	int index0 = index[0], index1 = index[1];
	if(index0 == index1)
	{
		total[index0] += time;
	}
	else
	{
		if(sum[index1] > sum[index0])
		{
			index0 = index[1];
			index1 = index[0];
		}

		tree[index1] = index0;
		sum[index0] += sum[index1];
		total[index0] += total[index1] + time;
	}
}

int main()
{
	int n, k;
	scanf("%d%d", &n, &k);

	int i, time;
	char c[2][5];

	for(i = 1; i <= n; i++)
	{
		getchar();
		scanf("%s%s%d", c[0], c[1], &time);
		
		buildrelation(c, time);
	}

	int root;
	vector<int> v;

	for(i = 1; i <= cur; i++)
	{
		if(tree[i] == -1 && sum[i] > 2 && total[i] > k)
		{
			v.push_back(i);
		}

		root = findroot(i);
		if(headindex[root] == 0 || weight[i] > weight[headindex[root]])
		{
			headindex[root] = i;
		}
	}

	int size = v.size();
	printf("%d\n", size);

	if(size > 0)
	{
		size = v.size();
		sort(v.begin(), v.end(), cmp);

		for(i = 0; i <= size - 1; i++)
		{
			print(v[i]);
		}
	}

	system("pause");
	return 0;
}

 

posted on 2025-11-23 17:02  王景迁  阅读(0)  评论(0)    收藏  举报

导航