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 (<=10000) 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 5Sample Output 1:
3 4 5Sample Input 2:
5 1 3 1 4 2 5 3 4Sample Output 2:
Error: 2 components
题意:这题求两个,一是有几个连通块,既可用dfs,又可用并查集。这里我用的dfs。
第二问求以哪个节点为根节点时,树的长度最高。因为本题n个节点n-1条边,只有一个连通块的话正好是一棵树。为了防止无向图回溯,我用的是vis数组,遍历每个未访问过子节点,vis赋true,对子节点再进行DFS,这个子节点处理完再把vis赋为false。
晴神的思路是设定pre,树只要不回溯无向连接之前的那个结点即可
AC代码:
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn=10001;
int n;
std::vector<int> node[maxn];
bool vis[maxn];
void dfs(int v){
memset(vis,0,n+1);
vis[v]=true;
for(int i=0;i<node[v].size();i++){
if(vis[node[v][i]]==false) { vis[node[v][i]]=true; dfs(node[v][i]);}
}
}
int h[maxn],max1[maxn];
int min1=0;
void dfs2(int v,int height){
vis[v]=true;
for(int i=0;i<node[v].size();i++){
// cout<<"v1 "<<v<<" "<<node[v][i]<<endl;
if(vis[node[v][i]]==false){
//vis[node[v][i]]=true;
// cout<<"v2 "<<v<<" "<<node[v][i]<<endl;
dfs2(node[v][i],height+1);
if(height+1>h[node[v][i]]) h[node[v][i]]=height+1;
if(height+1>min1){min1=height+1;}
vis[node[v][i]]=false;}
}
}
int main(){
freopen("E:\input.txt","r",stdin);
int n;
cin>>n;
for(int i=1;i<=n-1;i++){
int a,b;
cin>>a>>b;
node[a].push_back(b);
node[b].push_back(a);
}
dfs(1);
int cnt=1;
for(int i=1;i<=n;i++){
if(vis[i]==false) { ++cnt; dfs(i);}
}
int maxh=0;
if(cnt>1) printf("Error: %d components",cnt);
else{
for(int i=1;i<=n;i++){
memset(vis,0,maxn);
memset(h,0,maxn);
min1=0;
dfs2(i,1);
max1[i]=min1;
if(max1[i]>maxh) maxh=max1[i];
}
for(int i=1;i<=n;i++){
if(max1[i]==maxh) cout<<i<<endl;
}
}
}