1021 Deepest Root (25 分)
作者:互联网
不是原创???
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector<int> visited(10001), roots;
vector<vector<int>> G(10001);
int minH = 0;
void BFS( int v )
{
queue<int> q;
q.push(v);
visited[v] = 1;
int last = v, height = 0, w;
while( !q.empty() )
{
w = q.front();
q.pop();
for( int i = 0; i < G[w].size(); ++i )
{
if( !visited[ G[w][i] ] )
{
visited[ G[w][i] ] = 1;
q.push( G[w][i] );
}
}
if( w == last )
{
last = q.back();
++height;
}
}
if( height > minH )
{
minH = height;
roots.clear();
roots.push_back(v);
}
else if( height == minH )
roots.push_back(v);
}
int main()
{
int N, nComponent = 0;
scanf("%d", &N);
for( int i = 0, v1, v2; i < N - 1; ++i )
{
scanf("%d %d", &v1, &v2);
G[v1].push_back(v2);
G[v2].push_back(v1);
}
for( int i = 1; i <= N; ++i )
if( !visited[i] )
{
++nComponent;
BFS( i );
}
roots.clear();
if( nComponent > 1 )
{
printf("Error: %d components", nComponent);
return 0;
}
for( int i = 1; i <= N; ++i )
{
fill( visited.begin(), visited.end(), 0 );
BFS(i);
}
sort( roots.begin(), roots.end() );
for( int i = 0; i < roots.size(); ++i )
printf("%d%s", roots[i], i == roots.size() - 1 ? "":"\n");
}
标签:minH,1021,int,back,height,Deepest,push,Root,roots 来源: https://blog.csdn.net/qq_43749739/article/details/98473707