1021. Deepest Root (25)
A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is calledthe deepest root.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N-1 lines follow, each describes an edge by given the two adjacent nodes' numbers.
Output Specification:
For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print "Error: K components" where K is the number of connected components in the graph.
Sample Input 1:5 1 2 1 3 1 4 2 5Sample Output 1:
3 4 5Sample Input 2:
5 1 3 1 4 2 5 3 4Sample Output 2:
Error: 2 components
http://www.patest.cn/contests/pat-a-practise/1021
ac关键:进行多次的DFS,set<>集合应用
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<string>
#include<vector>
#include<set>
using namespace std;
const int INF=0x7fffffff;
const int N=10005;
int n;
vector<int> vt[N];
int fa[N];
int Find(int x){
if(x==fa[x])
return x;
return fa[x]=Find(fa[x]);
}
void Merge(int x,int y){
int xx=Find(x);
int yy=Find(y);
fa[yy]=xx;
}
int maxHeight;
int Height[N];
bool vis[N];
int tmpMaxId;
void DFS(int root,int h){
if(vis[root])
return;
vis[root]=true;
Height[root]=h;
if(h>maxHeight)
{
maxHeight=h;
tmpMaxId = root;
}
int len=vt[root].size();
for(int i=0;i<len;i++){
int v=vt[root][i];
DFS(v,h+1);
}
}
int main(){
//freopen("in.txt","r",stdin);
while(scanf("%d",&n)!=EOF){
int i;
int u,v;
for(i=1;i<=n;i++){
fa[i]=i;
vt[i].clear();
}
for(i=0;i<n-1;i++){
scanf("%d%d",&u,&v);
vt[u].push_back(v);
vt[v].push_back(u);
if(Find(u)!=Find(v))
Merge(u,v);
}
set<int> st;
for(i=1;i<=n;i++)
st.insert(Find(i));
int stlen=st.size();
if(stlen>1)
printf("Error: %d components\n",stlen);
else{
for(i=1;i<=n;i++)
vis[i]=false;
maxHeight=0;
tmpMaxId = -1;
DFS(1,1);
//
vector<int> vans;
/* for(i=1;i<=n;i++){
if(Height[i]==maxHeight)
vans.push_back(i);
}*/
int lenv=vans.size();
/*for(i=0;i<lenv;i++){
for(int j=1;j<=n;j++)
vis[j]=false;
DFS(vans[i],1);
}*/
maxHeight = -1;
for(int j=1;j<=n;j++)
vis[j]=false;
DFS(tmpMaxId, 1);
int tmpMax=maxHeight;
vans.clear();
for(i=1;i<=n;i++){
maxHeight=0;
for(int j=1;j<=n;j++)
vis[j]=false;
DFS(i,1);
if(maxHeight==tmpMax){
vans.push_back(i);
}
}
lenv=vans.size();
for(int i=0;i<lenv;i++)
cout<<vans[i]<<endl;
}
}//end while
return 0;
}