您的位置:首页 > 其它

1021. Deepest Root (25)(dfs+并查集)

2017-11-29 20:28 288 查看
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 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

题意:一个图寻找最长的路径是多长,输出最长路径的根节点,如果有多个就把根节点按升序输出,如果不是连通图则输出Error: 图的个数 components。用并查集判断连通图,用dfs寻找最长的路径

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int map[1010][1010],vis[1010],f[1010],deep[1010];
int n,sum;
int dfs(int t)
{
int Max=0;
vis[t] = 1;
for(int i=1;i<=n;i++)
{
if(!vis[i]&&map[t][i])
{
int count = dfs(i);
if(count>Max)
Max = count;
}
}
return Max+1;///长度应加上根节点所以还应+1
}
void init(int n)
{
for(int i=1;i<=n;i++)
{
f[i] = i;
}
}
int getf(int v)
{
if(v==f[v])
{
return v;
}
else
{
f[v] = getf(f[v]);
return f[v];
}
}
void merg(int u,int v)
{
int t1 = getf(u);
int t2 = getf(v);
if(t1!=t2)
f[t2] = t1;
4000

}
int main()
{
int i,j;
int u,v;
while(~scanf("%d",&n))
{

memset(map,0,sizeof(map));
init(n);
for(i=1;i<=n-1;i++)
{
scanf("%d%d",&u,&v);
merg(u,v);
map[u][v] = map[v][u] = 1;
}
sum = 0;
for(i=1;i<=n;i++)
{
if(f[i] == i)
sum++;///并查集寻找有几个图
}
if(sum>1)
{
printf("Error: %d components\n",sum);
}
else
{
for(i=1;i<=n;i++)
{
memset(vis,0,sizeof(vis));
deep[i] = dfs(i);///每个点作为根节点的时候路径有多长,存在deep里
}
int max = -1,pos;
for(i=1;i<=n;i++)
{
if(deep[i]>max)
{
max = deep[i];
pos = i;///找到最大的路径是多长
}
}
for(j=1;j<=n;j++)///按升序输出,从第一个开始一个一个比较
{
if(deep[j] == deep[pos])
printf("%d\n",j);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: