题目:
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思路:
1.先用并查集考察是否为同一树
2.再用深度优先搜索查找最深的节点
注意:
1.不能用邻接节点,否则会有测试点超时
代码:
#include<string.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int Max = 10001;
vector<int> linkmap[Max];
int node[Max] = { 0 };
//union-find: find root
int findroot(int r)
{
if (r != node[r])
{
findroot(node[r]);
}
else
return r;
};
//union-find: union
void unionnode(int r1, int r2)
{
node[r1] = findroot(r1);
node[r2] = findroot(r2);
if (node[r1] != node[r2])
{
if(node[r1]<node[r2])
node[r2] = node[r1];
else
node[r1] = node[r2];
}
return;
};
//depth first search
int visit[Max] = { 0 };
int dfs(int deep,int n,int N)
{
int i,d,maxd,tmp;
maxd = deep;
visit[n] = 1; //mark the node
for (i = 0; i <linkmap[n].size(); ++i)
{
tmp = linkmap[n][i];
if (!visit[tmp])
{
d=dfs(deep + 1, tmp, N);
if (d > maxd)
maxd = d;
}
}
return maxd;
}
int main()
{
int N;
cin >> N;
if (N == 1)
{
cout << 1 << endl;
}
else
{
//input
int i, n1, n2;
for (i = 1; i <= N; ++i)
{
node[i] = i;
}
for (i = 1; i < N; ++i)
{
cin >> n1 >> n2;
linkmap[n1].push_back(n2);
linkmap[n2].push_back(n1);
unionnode(n1, n2);
}
//use union-find
int comp = 0;
for (i = 1; i <= N; ++i)
{
if (i == node[i])
comp++;
}
if (comp > 1)
{
cout << "Error: " << comp << " components" << endl;
}
else
{
int j;
vector<int> result;
int R = 0;
int depth;
for (i = 1; i <= N; ++i)
{
if (linkmap[i].size()==1)
{
memset(visit, 0, sizeof(visit));
depth = dfs(0, i, N);//find the depth
if (depth > R)
{
R = depth;
result.clear();
result.push_back(i);
}
else if (depth == R)
{
result.push_back(i);
}
}
}
sort(result.begin(), result.end());
for (i = 0; i < result.size(); ++i)
cout << result[i] << endl;
}
}
system("pause");
return 0;
}