1021. Deepest Root (25)

#include <iostream>
#include <queue>
#include <vector>
#include <string.h>

using namespace std;

int vis[10010], sum[10010], tree[10010], level;
queue<int> q;
vector<int> v[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 buildrelation(int index[2])
{
	int i;
	for(i = 0; i <= 1; i++)
	{
		index[i] = findroot(index[i]);
	}

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

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

void bfs()
{
	int qsize = q.size(), vsize, cur, i, next;
	level++;

	while(qsize--)
	{
		cur = q.front();
		q.pop();

		vsize = v[cur].size();
		for(i = 0; i <= vsize - 1; i++)
		{
			next = v[cur][i];
			if(vis[next] == 0)
			{
				vis[next] = 1;
				q.push(next);
			}
		}
	}

	qsize = q.size();
	if(qsize > 0)
	{
		bfs();
	}
}

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

	return count;
}

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

	init(n);

	int i, a, b, index[2];
	for(i = 1; i <= n - 1; i++)
	{
		scanf("%d%d", &a, &b);
		
		v[a].push_back(b);
		v[b].push_back(a);

		index[0] = a;
		index[1] = b;

		buildrelation(index);
	}

	int count = getrootcount(n);
	if(count > 1)
	{
		printf("Error: %d components\n", count);
		return 0;
	}

	int max = 0;
	vector<int> res;

	for(i = 1; i <= n; i++)
	{
		memset(vis, 0, sizeof(vis));
		vis[i] = 1;

		level = 0;
		q.push(i);

		bfs();

		if(level > max)
		{
			max = level;

			res.clear();
			res.push_back(i);
		}
		else if(level == max)
		{
			res.push_back(i);
		}
	}

	int size = res.size();
	for(i = 0; i <= size - 1; i++)
	{
		printf("%d\n", res[i]);
	}

	system("pause");
	return 0;
}

 

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

导航