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 (≤104) 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
whereK
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
// 解题思路:
// 其实就是遍历得到树直径 混合 连通分量的个数
// 进行两次dfs
// 第一次:
// 只需要任选一个节点作为根节点开始遍历,得到深度最大的一个或多个节点
// 第二次:
// 再从这其中任选一个,再作为根节点遍历得到深度最大的节点 即是另一端// !需要注意的是,要进行去重,可能会在这两次中得到了相同的节点,这里用set保存 以去重
// pat的测试数据真是 把我这些思路总是不够全面的家伙 虐的够惨,处处是坑点啊
#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <cstring>
using namespace std;
inline void read(int &x)
{
register int f = 1; x = 0;
register char c = getchar();
while(c > '9' || c < '0')
{
if(c == '-') f = -1;
c = getchar();
}
while(c >= '0' && c <= '9')
{
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
x *= f;
}
const int maxn = 1e4 + 5;
set<int> ans;
vector<int> temp;
vector<int> mp[maxn];
bool vis[maxn];
int res = -1, cnt;
// op控制只单纯遍历 或是 求最深节点,分别用在求连通分量 和 直径端点
void dfs(int u, int depth, const int op)
{
bool flag = op;
vis[u] = true;
cnt++;
for(int i = 0; i < mp[u].size(); i++)
{
int v = mp[u][i];
if(!vis[v])
{
flag = false;
dfs(v, depth + 1, op);
}
}
// 只在求最深节点 且 为叶子节点下进行以下操作,减少不必要操作
if(flag)
{
if(depth > res)
{
temp.clear();
res = depth;
temp.push_back(u);
}
else if(depth == res)
{
temp.push_back(u);
}
}
}
int main()
{
// 读入数据建图
int n; read(n);
for(int u, v, i = 1; i < n; i++)
{
read(u); read(v);
mp[u].push_back(v);
mp[v].push_back(u);
}
// 第一次dfs
dfs(1, 1, 1);
// 如果遍历的节点数少于n,说明不止一个连通分量
if(cnt < n)
{
// dfs的次数则是连通分量的个数
int num = 1;
for(int i = 2; i <= n; i++)
{
if(!vis[i])
{
num++;
dfs(i, 1, 0);
}
}
printf("Error: %d components\n", num);
}
else
{
// 存入set,以复用vector temp
for(int i = 0; i < temp.size(); i++)
{
ans.insert(temp[i]);
}
// 清掉temp,重置比较深度器res 和 vis
temp.clear(); res = -1;
memset(vis, 0, sizeof(vis));
// 第二次dfs
dfs(*ans.begin(), 1, 1);
// 再存入
for(int i = 0; i < temp.size(); i++)
{
ans.insert(temp[i]);
}
// 输出结果
for(auto it = ans.begin(); it != ans.end(); it++)
{
printf("%d\n", *it);
}
}
return 0;
}