PAT 甲级 1021 Deepest Root (25 分)(bfs求树高,又可能存在part数part>2的情况)
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 (≤) 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
题意:
给出n个结点和n-1条边,问它们能否形成一棵n个结点的树,如果能,从中选出结点作为树根,使整棵树的高度最大。按升序输出所有满足要求的可以作为树根的结点。 如果不是一棵树,则输出cout<<"Error: "<<part<<" components";
思路:
bfs求高度,如果有多个部分,再bfs数有几个部分,part可能大于2。一开始没考虑,测试点2过不了。
5 1 2 1 3 3 1 2 3 Error: 3 components
AC代码:
#include<bits/stdc++.h> using namespace std; int n; vector<int>v[10005]; struct node{ int k;//节点的值 int h;//在第几层 }; queue<node>q; queue<int>ans; int in[100005];//在不在队列里 int main(){ cin>>n; for(int i=1;i<=n-1;i++){ v[i].clear(); } while(!q.empty()) q.pop(); while(!ans.empty()) ans.pop(); for(int i=1;i<=n-1;i++){ int x,y; cin>>x>>y; v[x].push_back(y); v[y].push_back(x); } int maxH=0; memset(in,0,sizeof(in)); int part=1; for(int i=1;i<=n;i++) { //以i为树根 int height=0; memset(in,0,sizeof(in)); node x; x.k=i; x.h=1; q.push(x); in[i]=1;//标记已访问 while(!q.empty()) { node x=q.front(); q.pop(); height=max(height,x.h);//更新高度 for(int j=0;j<v[x.k].size();j++)//遍历与 x.k相连的节点 { int k1=v[x.k].at(j); if(in[k1])//被访问过了 { continue; } node y; y.k=k1; y.h=x.h+1;//新的一层高度+1再放进队列 q.push(y); in[k1]=1; } } //先检查是不是一个块的 for(int j=1;j<=n;j++) { if(in[j]!=1) { part=0; break; } } if(!part) { break; } //cout<<i<<" "<<height<<endl; //更新高度 if(height>maxH) { maxH=height; while(!ans.empty()) ans.pop();//更新了就清空 ans.push(i); }else if(height==maxH) { ans.push(i); } } if(!part){ part=1; for(int j=1;j<=n;j++) {//bfs数数有多少块 if(in[j]!=1) { part++;//块数+1 node x; x.k=j; x.h=1; q.push(x); in[j]=1; while(!q.empty()) { node x=q.front(); q.pop(); for(int p=0;p<v[x.k].size();p++) { int k1=v[x.k].at(p); if(in[k1]) { continue; } node y; y.k=k1; y.h=x.h+1; q.push(y); in[k1]=1; } } } } cout<<"Error: "<<part<<" components"; }else{ while(!ans.empty()){ cout<<ans.front()<<endl; ans.pop(); } } return 0; }