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
题意:给你一个图,若是树,输出它最深层的节点,不是数,输出有多少个连通分量。
解析:dfs深搜,
1.判断是否是树。
2.找出最深节点,遍历每个节点,从每个节点出发,到达最深处,若步数是最深,则说明是该节点是最深层的节点。
注意要初始化vis和maxdeep
#include<bits/stdc++.h>
using namespace std;
#define e exp(1)
#define pi acos(-1)
#define mod 1000000007
#define inf 0x3f3f3f3f
#define ll long long
#define ull unsigned long long
#define mem(a,b) memset(a,b,sizeof(a))
int gcd(int a,int b){return b?gcd(b,a%b):a;}
const int maxn=1e4+5;
int n,ans,maxdeep;
vector<int>ve[maxn];
int vis[maxn];
int deep[maxn];
void dfs1(int step)
{
vis[step]=1;
for(int i=0; i<ve[step].size(); i++)
{
if(!vis[ve[step][i]])
{
dfs1(ve[step][i]);
}
}
}
void dfs2(int step,int cnt)
{
maxdeep=max(maxdeep,cnt);
vis[step]=1;
for(int i=0; i<ve[step].size(); i++)
{
if(!vis[ve[step][i]])
{
dfs2(ve[step][i],cnt+1);
}
}
}
int main()
{
scanf("%d",&n);
int x,y;
for(int i=0; i<n-1; i++)
{
scanf("%d%d",&x,&y);
ve[x].push_back(y);
ve[y].push_back(x);
}
ans=0;
for(int i=1; i<=n; i++)
{
if(!vis[i])
{//要是是树一定不会出现环,因为是n-1条边
dfs1(i);
ans++;
}
}
if(ans>1)
{
printf("Error: %d components\n",ans);
}
else
{
for(int i=1; i<=n; i++)
{
mem(vis,0);
maxdeep=0;
dfs2(i,1);
deep[i]=maxdeep;
}
for(int i=1; i<=n; i++)
{
maxdeep=max(maxdeep,deep[i]);
}
for(int i=1; i<=n; i++)
{
if(deep[i]==maxdeep)printf("%d\n",i);
}
}
return 0;
}