1021. Deepest Root (25)
时间限制
1500 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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 called the 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 5
Sample Output 1:
3
4
5
Sample Input 2:
5
1 3
1 4
2 5
3 4
Sample Output 2:
Error: 2 components
提交代码
这道题要注意一点要用邻接表存储图,如果用邻接矩阵会超时(稀疏图)
第一次写有返回值的DFS,还不是很熟练
#include<iostream> #include<cstdio> #include<cstring> #include<vector> #include<algorithm> using namespace std; const int maxn=10001; bool vis[maxn]; int a[maxn]; int n; int cnt=0; vector<int> ma[maxn];//邻接表 int d[maxn];//计算以这个点为树根时的最大深度 int dfs(int s)//dfs表示以S为起点所能达到的最大深度 { int ans=0; if(vis[s])return 0;//这个点已经被访问过,明显以这个点的最大深度是0 vis[s]=true; int m=ma[s].size(); for(int i=0; i<m; i++) { if(!vis[ma[s][i]]) { int tmp=dfs(ma[s][i]);//以当前点为起点访问能到达的最大的深度,也就是找出S的邻接点里的,深度,能达到的最大的 ans=max(ans,tmp);//ans记录下最大的深度即可 } } return ans+1;//能到这里说明以S点能到达的深度可以加一,也就是S相邻的顶点里的深度,最大值,加上S点,所以就是ans+1 } void init(int n)//这是并查集的初始化 { for(int i=0; i<=n; i++) a[i]=i; } int find(int x)//并查集查找X的父亲,带路径压缩 { if(a[x]!=x) a[x]=find(a[x]); return a[x]; } void unio(int x,int y)//合并X,Y到一起 { x=find(x); y=find(y); if(a[x]==a[y])return ; a[x]=y; } int main() { int i,j,k,t; // freopen("in.txt","r",stdin); cin>>n; init(n); for(i=1; i<n; i++) { int s,e; cin>>s>>e; unio(s,e); ma[s].push_back(e); ma[e].push_back(s); } int sum=0;//判断连通分量的个数 for(i=1; i<=n; i++) { if(a[i]==i)sum++; } if(sum>1) { printf("Error: %d components\n",sum); return 0; } else for(i=1; i<=n; i++) { memset(vis,0,sizeof(vis)); d[i]=dfs(i); } int maxv=-1;int index=0; for(i=1;i<=n;i++)if(d[i]>maxv){maxv=d[i];index=i;} for(j=1;j<=n;j++)if(d[j]==d[index]) printf("%d\n",j); }