PAT 1021 Deepest Root

个人学习记录,代码难免不尽人意。
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 (≤10 4 ) 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 
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn=10100;
const int INF=1000000000;
vector<int> G[maxn];
bool visit[maxn]={false};
int height=0;
void dfs(int n){
	visit[n]=true;
	for(int i=0;i<G[n].size();i++){
		if(!visit[G[n][i]]){
			dfs(G[n][i]);
		}
	}
	return;
}
int res=0;
void dfsheight(int n,int height){
	visit[n]=true;
	if(height>res) res=height;
	for(int i=0;i<G[n].size();i++){
		if(!visit[G[n][i]]){
			dfsheight(G[n][i],height+1);
		}
	}
	return;
}
int main(){
  int n;
  scanf("%d",&n);
  for(int i=0;i<n-1;i++){
  	int a,b;
  	scanf("%d %d",&a,&b);
	G[a].push_back(b);
	G[b].push_back(a); 
  }
  int block=0;
  for(int i=1;i<=n;i++){
    if(!visit[i]){
    	dfs(i);
    	block++;
	}
  }
  if(block>1){
  	printf("Error: %d components",block);
  	return 0;
  }
  
  vector<int> v;
  int max=-1;
  for(int i=1;i<=n;i++){

  fill(visit+1,visit+1+n,false);
  	  res=0;
  	  	
  	  dfsheight(i,0);
  	  if(max<res){
  	  	max=res;
  	  	v.clear();
  	  	v.push_back(i);
		}
	   else if(max==res){//这个地方手误写成了max=res卡了好久
	   	v.push_back(i);
	   }
  }
  for(int i=0;i<v.size();i++){
  	printf("%d\n",v[i]);
  }

}

这道题还蛮有意思的,注意题目要求n<=10000,因此不能用邻接矩阵来做必须用邻接表。
其次,题目说给了n-1条边,因此我们可以排除连通块为1且有回路的情况,也就是说可以不用考虑回路。具体做法是先判断连通块是否为1,是则结束,不是则进入下一步dfs处理
各位一定要注意写if条件的时候等于是“==”,我有好几次都只写了一个=导致检查了半天错误,大家切记。

你可能感兴趣的:(PTA,深度优先,算法,c++)