1021. Deepest Root (25)

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 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

题目大意:如果是连通图,则求连通图中点Vi到点Vj所有路径中最长(包含多对)的并打印出所有Vi与Vj。如果是非连通图,则打印出有几个子图。用并查集判断是否是连通图,随后用搜索来求最长路。
#include<iostream>
#include<stdio.h>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
#define max 10002
int visit[max];
int a[max];
int N;
int distan[max];
vector<int>map[max];
int find(int x){
if(a[x]== x)return x;
find(a[x]);
}
void unio(int x,int y){
x = find(x);
y = find(y);
if(x != y){
a[x] = y;
}
}
int DFS(int key){
if(visit[key]==1)return 0;
visit[key]=1;
int i;
int sum = 0;
int m = map[key].size();
for(i=0;i<m;i++){
if(visit[map[key][i]]==0){
int tmp = DFS(map[key][i]);
if(sum < tmp){
sum = tmp;
}
}
}
return sum+1;
}
int main(){
scanf("%d",&N);
int i,j,t;
int s,d;
for(i=1;i<=N;i++){
a[i]=i;
}
for(i=1;i<N;i++){
scanf("%d%d",&s,&d);
unio(s,d);
map[s].push_back(d);
map[d].push_back(s);
}
int flag=0;
for(i=1;i<=N;i++){
if(a[i]==i){
flag++;
}
}
if(flag>1){
printf("Error: %d components",flag);
} else{
for(i=1;i<=N;i++){
memset(visit,0,sizeof(visit));
distan[i]=DFS(i);
}
int a=-1,b=0;
for(i=1;i<=N;i++){
if(distan[i]>a){
a=distan[i];
b=i;
}
}
for(i=1;i<=N;i++){
if(distan[i] == distan[b]){
printf("%d\n",i);
}
}
}
return 0;
}

  


上一篇:A1021. Deepest Root


下一篇:PAT 甲级 1021 Deepest Root