5-8 File Transfer (25分)

#include <iostream>

using namespace std;

int tree[10010], sum[10010];

void init(int n)
{
	int i;
	for(i = 1; i <= n; i++)
	{
		tree[i] = -1;
		sum[i] = 1;
	}
}

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

void setroot(int index[2])
{
	index[0] = findroot(index[0]);
	index[1] = findroot(index[1]);
}

void buildrelation(int index[2])
{
	setroot(index);

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

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

int getrootcount(int n)
{
	int i, count = 0;
	for(i = 1; i <= n; i++)
	{
		if(tree[i] == -1)
		{
			count++;
		}
	}

	return count;
}

int check(int index[2])
{
	setroot(index);

	if(index[0] == index[1])
	{
		return 1;
	}

	return 0;
}

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

	init(n);

	char ch;
	int index[2], i;

	while(1)
	{
		getchar();
		scanf("%c", &ch);

		if(ch == 'S')
		{
			break;
		}

		scanf("%d%d", &index[0], &index[1]);

		if(ch == 'C')
		{
			if(check(index) == 1)
			{
				printf("yes\n");
			}
			else
			{
				printf("no\n");
			}
		}
		else
		{
			buildrelation(index);
		}
	}

	int count = getrootcount(n);
	if(count == 1)
	{
		printf("The network is connected.\n");
	}
	else
	{
		printf("There are %d components.\n", count);
	}

	system("pause");
	return 0;
}

 

posted on 2025-11-29 14:57  王景迁  阅读(0)  评论(0)    收藏  举报

导航