PAT A1021. Deepest Root (25)

来源:互联网 发布:南通纯电动汽车知豆 编辑:程序博客网 时间:2024/06/02 04:22

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:
51 21 31 42 5
Sample Output 1:
345
Sample Input 2:
51 31 42 53 4
Sample Output 2:
Error: 2 components
#include <cstdio>#include <algorithm>#include <vector>using namespace std;const int Max = 11110;int n,m,k;int Depth[Max]={0};int De[Max]={0},de=0;int block=0;struct Graph{vector<int> ins;int dep;}G[Max];bool Visit[Max];void DFS(int temp,int h){if(Visit[temp]==true) return ;Visit[temp]=true;G[temp].dep=h;if(G[temp].dep>G[k].dep){k=temp;}for(int i=0;i<G[temp].ins.size();i++){if(Visit[G[temp].ins[i]]==false)DFS(G[temp].ins[i],h+1);}}bool cmp(int a,int b){if(Depth[a]!=Depth[b]) return Depth[a]>Depth[b];else return a<b;}int main(){scanf("%d",&n);for(int i=1;i<n;i++){int temp, ans;    scanf("%d%d",&temp,&ans);G[temp].ins.push_back(ans);G[ans].ins.push_back(temp);G[ans].dep=G[temp].dep=1;}G[0].dep=-1;for(int i=1;i<=n;i++){int num=0,he=1;block=0;for(int j=1;j<=n;j++){Visit[j]=false;G[j].dep=1;}DFS(i,G[i].dep);block++;for(int j=1;j<=n;j++){if(j!=i&&Visit[j]==false){DFS(j,G[j].dep);block++;}}int hhh=-1;for(int j=1;j<=n;j++){if(G[j].dep>hhh){hhh=G[j].dep;}}if(block>1){i=n+1;}else {Depth[i]=hhh;De[de++]=i;}}if(block>1){printf("Error: %d components\n",block);}else {sort(De,De+de,cmp);for(int i=0;i<n;i++){printf("%d",De[i]);if(Depth[De[i+1]]==Depth[De[i]]){printf("\n");}else {printf("\n");break;}}}system("pause");return 0;}

0 0
原创粉丝点击