1. 程式人生 > >PAT 1021

PAT 1021

#include 
#include 
using namespace std;

#define inf 999999999

int N;

struct node
{
	vector e;
};

node* nodes[10010];

int e_n[10010];
int res[10010];
bool visit[10010];
int family[10010];

int deep(int root)
{
	int dp = 0;
	for (auto it : nodes[root]->e)
	{
		if (!visit[it])
		{
			visit[it] = true;
			int tp = deep(it);
			visit[it] = false;
			if (tp > dp) dp = tp;
		}
	}

	return dp+1;
}

int root(int i)
{
	if (family[i] == i) return i;

	int	temp = root(family[i]);
	family[i] = temp;
	return temp;
}
void join(int i, int j)
{
	family[root(i)] = root(j);
}

int main()
{
	fill(visit, visit + 10010, false);
	visit[0] = true;
	fill(res, res + 10010, -1);
	fill(e_n, e_n + 10010, 0);
	cin >> N;
	for (int i = 1; i <= N; i++)
	{
		family[i] = i;
		nodes[i] = new node;
		nodes[i]->id = i;
	}
	if (N == 1) cout << 1 << endl;

	for (int i = 1; i < N; i++)
	{
		int tp1, tp2;
		cin >> tp1 >> tp2;
		
		nodes[tp1]->e.push_back(tp2);
		nodes[tp2]->e.push_back(tp1);

		e_n[tp1] += 1;
		e_n[tp2] += 1;

		join(tp1, tp2);

	}
	int part = 1;
	vector token;
	token.push_back(root(1));
	for (int i = 2; i <= N; i++)
	{
		bool flag = false;
		for (auto it : token)
		{
			if (root(i) == it) flag = true;
		}
		if (!flag)
		{
			token.push_back(root(i));
			part++;
		}
	}
	if (part != 1)
	{
		cout << "Error: " << part << " components";
		system("PAUSE");
		return 0;
	}

	for (int i = 1; i <= N; i++)
	{
		if (e_n[i] == 1)
		{
			visit[i] = true;
			res[i] = deep(i);
			visit[i] = false;
		}
	}
	int max = 0;
	for (int i = 1; i <= N; i++)
	{
		if (res[i] > max)
		{
			max = res[i];
		}
	}
	for (int i = 1; i <= N; i++)
	{
		if (res[i] == max)
		{
			cout << i << endl;
		}
	}




	system("PAUSE");
}