【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 (≤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

解题思路:

题目给出N个节点,节点编号是1到N,给出N-1条边。让我们判断是不是一棵树,如果是的话找出深度最深的节点,不唯一的时候按编号从小到大输出。

首先判断是否是一颗树,可以用dfs算法来判断,如果是一颗树的话,用dfs求出的它的连通分量一定是1。然后是最深的节点,也可以用dfs算法,多加两个变量,一个是d用来统计深度,一个是root用来记录此时的根节点。而深度其实是相对的,因为树可以正立也可以倒立,所以只要用deep来存储根节点的深度就行,只要根节点的深度最深,那么在反过来的情况下,这个根节点可以变成深度最深的节点。

易错点:

最深的节点并不是指叶子节点。而是把每一个节点都单独看成是根节点,然后找到最深的节点。如果你只是去找叶子节点的话,输出样例里面的测试点0,1会出错。

最大的深度是指每个节点作为根节点时找到的所有里面的最大深度,而不是输出每个节点里的最大深度。

代码:

#include<bits/stdc++.h>
using namespace std;
vector<int> G[10001];
int visit[10001]={0};

int MAX=0;//最大的深度 
int deep[10001]={0};//存储每个节点作为根时的深度 
//因为树可以倒置,所以它作为根时树的深度,就是它的深度
 
void dfs(int x){//dfs算法用来计算连通分量的个数 
	for(int i=0;i<G[x].size();i++){
		if(visit[G[x][i]]) continue;
		visit[G[x][i]]=1;
		dfs(G[x][i]);
	}
}
void dfs_deep(int x,int d,int root){
	if(visit[x]==0){
		visit[x]=1;
		for(int i=0;i<G[x].size();i++){
			if(visit[G[x][i]]==0){
				deep[root] = max(deep[root],d+1);
				MAX = max(MAX,deep[root]);
				dfs_deep(G[x][i],d+1,root);
			}
		}
	}
}

int main(){
	int N;
	cin>>N;
	for(int i=0;i<N-1;i++){
		int a,b;
		cin>>a>>b;
		G[a].push_back(b);
		G[b].push_back(a);
	}
	int tol=0;
	for(int i=1;i<=N;i++){
		if(visit[i]) continue;//当访问过时,继续执行。 
		//第一次dfs后如果仍有未访问过的节点,那么再次dfs,且连通分量加一
		dfs(i);
		tol++; 
	}
	if(tol>1) cout<<"Error: "<<tol<<" components";
	else{
		for(int i=1;i<=N;i++){
			fill(visit,visit+10001,0);//每次都要将访问置零 
			dfs_deep(i,0,i);
		}
		for(int i=1;i<=N;i++){
			if(deep[i]==MAX) cout<<i<<endl;
		}
	}
	return 0;
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值