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 (<=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
我的代码(解法一):
(使用算法:广度优先搜索加并查集。此代码在甲级真题上提交通过(时限1500毫秒),但是在牛客网上提交运行超时(时限1000毫秒))
#include<iostream>
#include<set>
#include<queue>
#include<vector>
using namespace std;
set<int>s;
vector<int>v[10001];
int f[10001],n,x,y,i,maxx=0;
int find(int x)
{
if(f[x]==x) return x;
else return f[x]=find(f[x]);
}
void mer(int x,int y)
{
int a=find(x),b=find(y);
if(a!=b) f[a]=b;
}
int bfs(int s)
{
int i,vis[10001]={0},last=s,tail,level=0;
queue<int>q;
q.push(s);
vis[s]=1;
while(!q.empty())
{
s=q.front();
q.pop();
for(i=0;i<v[s].size();i++)
{
if(vis[v[s][i]]==0)
{
vis[v[s][i]]=1;
q.push(v[s][i]);
tail=v[s][i];
}
}
if(last==s)
{
level++;
last=tail;
}
}
return level;
}
int main()
{
scanf("%d",&n);
for(i=1;i<=n;i++) f[i]=i;
for(i=0;i<n-1;i++)
{
scanf("%d%d",&x,&y);
v[x].push_back(y);
v[y].push_back(x);
mer(x,y);
}
for(i=1;i<=n;i++) s.insert(find(i));
if(s.size()>1)
{
printf("Error: %d components\n",s.size());
return 0;
}
for(i=1;i<=n;i++)
{
if(bfs(i)>maxx) maxx=bfs(i);
}
for(i=1;i<=n;i++)
{
if(bfs(i)==maxx) printf("%d\n",i);
}
return 0;
}
提交结果:
我的代码(解法二):
(使用算法:深度优先搜素加并查集。此代码只能在甲级真题上提交通过,在牛客网上提交运行超时)
#include<iostream>
#include<vector>
#include<set>
#include<memory.h>
using namespace std;
int f[10001],vis[10001],h[10001],n,i,x,y,maxx=0;
set<int>s;
vector<int>v[10001];
int find(int x)
{
if(f[x]==x) return x;
else return f[x]=find(f[x]);
}
void mer(int x,int y)
{
int a=find(x),b=find(y);
if(a!=b) f[a]=b;
}
int dfs(int x)
{
int i,max=0;
if(vis[x]==1) return 0;
vis[x]=1;
for(i=0;i<v[x].size();i++)
{
if(vis[v[x][i]]==0)
{
int t=dfs(v[x][i]);
if(t>max) max=t;
}
}
return max+1;
}
int main()
{
scanf("%d",&n);
for(i=1;i<=n;i++) f[i]=i;
for(i=0;i<n-1;i++)
{
scanf("%d %d",&x,&y);
mer(x,y);
v[x].push_back(y);
v[y].push_back(x);
}
for(i=1;i<=n;i++) s.insert(find(i));
if(s.size()>1)
{
printf("Error: %d components\n",s.size());
return 0;
}
for(i=1;i<=n;i++)
{
memset(vis,0,sizeof(vis));
h[i]=dfs(i);
if(h[i]>maxx) maxx=h[i];
}
for(i=1;i<=n;i++)
{
if(h[i]==maxx) cout<<i<<endl;
}
return 0;
}
提交结果: