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 (≤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
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
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4+10;
std::vector<std::vector<int> > vec(maxn);
bool vis[maxn];
int height[maxn];
int num = 0;
int N;
void dfs(int pos){
vis[pos] = true;
for(auto it = vec[pos].begin();it!=vec[pos].end();it++)
if(vis[*it] == false)
dfs(*it);
}
int calc(int pos,int num){
int max_val = num;
vis[pos] = true;
for(auto it = vec[pos].begin();it!=vec[pos].end();it++)
if(vis[*it]==false)
max_val = max(max_val,calc(*it,num+1));
return max_val;
}
int main(int argc, char const *argv[])
{
cin>>N;
for (int i = 0; i < N-1; ++i)
{
int u,v;
cin>>u>>v;
vec[u].push_back(v);
vec[v].push_back(u);
}
for(int i = 1;i<=N;i++)
if(vis[i] == false){
dfs(i);
num++;
}
if(num >1){
cout<<"Error: "<<num<<" components"<<endl;
return 0;
}
int max_val = 0;
for(int i = 1;i<=N;i++)
{
memset(vis,0,sizeof(vis));
height[i] = calc(i,0);
max_val = max(max_val,height[i]);
}
for (int i = 1; i <=N; ++i)
{
if(height[i] == max_val)
cout<<i<<endl;
}
return 0;
}
解题思路
先对每个顶点都进行DFS遍历计算联通数量,大于1直接就不用搜了。然后对每个节点进行其最大深度的计算,本代码中用了分治的思想, max_val = max(max_val,calc(j,num+1)),递归第i个节点的邻接节点j 计算这个节点往下搜索的深度最大值,然后保存下来并进行比较,题目返回最大深度。