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 5Sample Output 1:
3 4 5Sample Input 2:
5 1 3 1 4 2 5 3 4Sample Output 2:
Error: 2 components
# include <cstdio>
# include <iostream>
# include <cstring>
# include <algorithm>
# include <set>
# include <vector>
using namespace std;
const int size = 10000;
const int debug = 1;
class DisjointSet
{
private:
int *T,size,sum;
int FindRoot(int i){return T[i] < 0 ? i : (T[i] = FindRoot(T[i]));}
public:
DisjointSet(int _size):size(_size)
{
T = new int[size];
Init();
}
void Init(){sum = size;memset(T,-1,sizeof(int)*size);}
bool Unioned(int i,int j){return FindRoot(i)==FindRoot(j);}
void Union(int i,int j)
{
if ( (i = FindRoot(i) ) != ( j = FindRoot(j) ) )
{
T[i] = T[i] + T[j];
T[j] = i;
sum--;
}
}
int FindSum(int i){return -T[FindRoot(i)];}
int SumOfUnits(){return sum;}
~DisjointSet(){delete[] T;}
};
vector<int> v[size];
int vis[size];
void dfs(int i,int dist,int &MAX)
{
vis[i] = dist;
MAX = max(MAX,vis[i]);
for (int k=0;k<v[i].size();k++)
if (vis[v[i][k]]==-1)
dfs(v[i][k],dist+1,MAX);
}
int main()
{
int i,j,temp;
int n;
scanf("%d",&n);
DisjointSet ds(n);
for (i=0;i<n-1;i++)
{
int a,b;
scanf("%d%d",&a,&b);a--,b--;
v[a].push_back(b);
v[b].push_back(a);
ds.Union(a,b);
}
if (ds.SumOfUnits() == 1)
{
int start,Max;
set<int> s;
for (Max=start=i=0;i<2;i++)
{
memset(vis,-1,sizeof(vis));
dfs(start,0,Max);
for (j=0;j<n;j++)
if (vis[j]==Max)
s.insert(j);
start = *s.begin();
}
for (set<int>::iterator it = s.begin();it!=s.end();it++)
printf("%d\n",(*it)+1);
}
else
printf("Error: %d components\n",ds.SumOfUnits());
return 0;
}