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

adjacent 英[əˈdʒeɪsnt]
美[əˈdʒeɪsnt]
adj. 与…毗连的; 邻近的;(今天算法课正好看到这个单词,有缘

acyclic 英[ˌeɪˈsaɪklɪk]
美[ˌeɪˈsaɪklɪk]
adj. 非周期的; 非循环的; 无环的; 非环状的;
首先是题意。。。没读懂,看中文才懂得,connected components 我以为是有几个部分相连接。。。可能还是做得少

算是自己独立做出来的吧(开心),因为我是按类型做的,所以这就是连通图的题目。但是不完美,才23分,另外的2分是超时。。。我也就不求甚解了,感觉理解上没啥大的错误,有时候看人题解也是很累的,网上,算法笔记上有的都是用并查集做的,貌似并查集在图的连通性还是很常用的,但是我并不怎么喜欢,
嘛,思路很简单,我的代码也不复杂,就是理解题意很重要。

#include<iostream>
#include<string.h>
#include<set>
#include<vector>
const int maxn =10000;
using namespace std;
vector<int> G[maxn];
bool vis[maxn]={false};
int maxx,n;
set<int> s; 
void dfs(int s){
	if(!G[s].size()) return ;
	vis[s] = true;
	for(int i=0;i<G[s].size();i++){
		if(!vis[ G[s][i] ])
		dfs(G[s][i]);
	}
}
void dfss(int v,int max1,int init){
	if(max1 > maxx){
		s.clear();
		s.insert(init);
		maxx=max1;
	}
	else if(max1 == maxx){
		s.insert(init);
	}
	vis[v] = true;
	max1++;
	for(int i=0;i<G[v].size();i++){
		if(!vis[ G[v][i] ])
		dfss(G[v][i],max1,init);
	}
}
int main(){
	cin>>n;
	for(int i=1;i<n;i++){
		int a,b;
		cin>>a>>b;
		G[a].push_back(b);
		G[b].push_back(a);
	}
	int blocks=0;
	 for(int i=1;i<=n;i++){
	 	if(!vis[i]){
	 		blocks++;
	 		dfs(i);
		 }
	 }
	 if(blocks > 1) printf("Error: %d components",blocks);
	 else{
	 	
	 	for(int i=1;i<=n;i++){
	 		memset(vis,0,sizeof(vis));
	 		int max1=0;
	 		dfss(i,max1,i);
		 }
	 }
	 set<int> :: iterator it;
	 for(it = s.begin();it!=s.end();it++){
	 	cout<<*it<<endl;
	 }
	return 0;
} 

在这里插入图片描述
慢慢变强的感觉很开心o( ̄▽ ̄)ブ

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值