题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1021
// dfs求树的深度:递归返回
// bfs求树的深度:队列空时得树的深度
/* 邻接表的dfs
vector<int> adj[SIZE];//存放相连节点
int dfs(int s)
{
int i, max=-1;
for(i=0; i<adj[s].size(); i++)
{
if(visit[adj[s][i]] == false)
{
visit[adj[s][i]]=true;
int t=dfs(adj[s][i]);
max= max > t ? max :t;
}
}
return max+1;
}
*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#define SIZE 10000+10
using namespace std;
struct Node
{
//int id;
int high;
};
int map[SIZE][SIZE];//树用邻接矩阵太浪费了,内存超限,应当使用邻接表
int n, k=1;
int fa[SIZE];
Node buf[SIZE];
bool visit[SIZE];
int numOfTrees();
int getFa(int x);
void Init();
void Input();
void Init()
{
int i;
for(i=1; i<=n; i++)
{
fa[i]=i;
buf[i].high=1;//根节点高度为1
visit[i]=false;
int j;
for(j=1; j<=n; j++)
{
map[i][j]=-1;
}
}
}
int getFa(int x)
{
if(x == fa[x])
return x;
else
fa[x] = getFa(fa[x]);
return fa[x];
}
int numOfTrees()
{
int i, num=0;
for(i=1; i<=n;i++)
{
int j;
for(j=i+1; j<=n; j++)
{
int a=getFa(i);
int b=getFa(j);
if(a != b)
{
num++;
fa[a] = b;
}//合并
}
}
return num;
}
void Input()
{
int i;
int c1, c2;
for(i=1; i<n; i++)
{
scanf("%d%d", &c1, &c2);
map[c1][c2]=map[c2][c1] = 1;
int a=getFa(c1);
int b=getFa(c2);
if(a != b)
{
fa[a]=b;
}//合并
}//n-1条边
}
int dfs(int node)
{
int t_high=0, mhigh=-1;
for(int j=1; j<=n; j++)
{
if(map[node][j] == 1)
{
if(j==node || visit[j] == true)
{
continue;
}
else
{
visit[j]=true;
t_high=dfs(j);
mhigh = mhigh>t_high ? mhigh:t_high;//记录子节点中最大高度
}
}
}
return mhigh+1;//返回自己的高度
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
// freopen("E:\\out.txt", "w", stdout);
#endif
scanf("%d", &n);
Init();
Input();
k=numOfTrees()+1;
if(k > 1)
{
printf("Error: %d components\n", k);
return 0;
}
//only a tree
int i;
for(i=1; i<=n;i++)
{
memset(visit, false, sizeof(visit));
visit[i]=true;//忘记出大问题呢
buf[i].high = dfs(i)+1;
}
int maxhigh=-1;
for(i=1;i<=n; i++)
{
//printf("%d\n", buf[i].high);
maxhigh = maxhigh>buf[i].high ? maxhigh:buf[i].high;
}
//printf("max:%d\n", maxhigh);
for(i=1;i<=n; i++)
{
if(maxhigh == buf[i].high)
{
printf("%d\n", i);
}
}
return 0;
}