欢迎大家关注我的公众号,里面不定时分享PAT-A/B代码~
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 (≤104) 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
代码:
#include<iostream>
#include<vector>
#include<cstring>
#include<queue>
#include<algorithm>
#include<set>
using namespace std;
int N;
bool vis[10010];
vector<int > adj[10010];//邻接表
set<int > root;//高度最大的树的根结点;
int max_height=0;
int H[10010]={0};
bool cmp(int a,int b)
{
return a>b;
}
int BFS(int j)
{
memset(H,0,sizeof(H));
queue<int > Q;
Q.push(j);
vis[j]=true;
H[j]=1;
int hh=1;
while(!Q.empty())
{
int t=Q.front();
Q.pop();
for(int i=0;i<adj[t].size();i++)
if(vis[adj[t][i]]==false)
{
H[adj[t][i]]=H[t]+1;
if(hh<H[t]+1)
hh=H[t]+1;
Q.push(adj[t][i]);
vis[adj[t][i]]=true;
}
}
return hh;
}
void root_tree(int i,int &height,int &component)
{
component=1;
memset(vis,false,sizeof(vis));
height=BFS(i);
for(int j=1;j<=N;j++)
{
if(vis[j]==false)
{
component++;
height=BFS(j);
}
}
}
int main()
{
scanf("%d",&N);
for(int i=1;i<N;i++)
{
int a,b;
scanf("%d%d",&a,&b);
adj[a].push_back(b);
adj[b].push_back(a);
}
for(int i=1;i<=N;i++)
{
int height,component;
root_tree(i,height,component);
if(component>1)
{
printf("Error: %d components",component);
return 0;
}
else
{
if(height>max_height)
{
root.clear();
root.insert(i);
max_height=height;
}
else if(height==max_height)
root.insert(i);
}
}
for(set<int>::iterator it=root.begin();it!=root.end();it++)
printf("%d\n",*it);
return 0;
}