這道題沒啥花裏胡哨,就是基本的圖(或者說樹)的遍歷。
因爲N是10^4,如果用鄰接矩陣的話可能會超時,所以這裏用的鄰接表的存儲方式。
用dfs查連通分量數
用bfs計算最深的根層數
bfs計算層數使用的方法是在每一層的後面將一個特殊點入隊作爲層的分隔點,在本題中這個點就是0,因爲結點都是大於0的。
ps:我又來偷懶了,用set存結點就不用再排序了
//DFS+BFS
const int maxn = 10000 + 5;
int n;
int v[maxn];
vector<int> G[maxn];
set<int> ans;
queue<int> q;
void dfs(int x){
v[x] = 1;
int t = G[x].size();
for(int i=0;i<t;i++){
if(!v[G[x][i]]) dfs(G[x][i]);
}
}
//因爲沒有0結點,所以借用0作爲層之間的分界點
//每層後面跟個0用來分層
int bfs(int i){
int deep = 0;
while(!q.empty()) q.pop();
memset(v,0,sizeof(v));
q.push(i);
q.push(0);
while(!q.empty()){
int r = q.front();
q.pop();
if(r == 0){
if(q.empty()) break;
deep++;
q.push(0);
continue;
}
v[r] = 1;
for(int i=0;i<G[r].size();++i){
if(!v[G[r][i]]){
q.push(G[r][i]);
}
}
}
return deep;
}
void process(){
ans.clear();
int maxx = 0;
for(int i=1;i<=n;++i){
int t = bfs(i);
if(maxx > t) continue;
else if(maxx == t) ans.insert(i);
else {
ans.clear();
ans.insert(i);
maxx = t;
}
}
for(set<int>::iterator it = ans.begin();it!=ans.end();++it)
printf("%d\n",*it);
}
int main()
{
int x,y,e,con;
scanf("%d",&n);
for(int i=0;i<n-1;i++){
scanf("%d%d",&x,&y);
G[x].push_back(y);
G[y].push_back(x);
}
memset(v,0,sizeof(v));
e = 0;
con = 0;
for(int i=1;i<=n;i++){
if(!v[i]){
dfs(i);
con++;
}
}
if(con>1) printf("Error: %d components\n",con);
else process();
return 0;
}