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");
}
上一篇:python – Pandas DataFrame计算重复行并填充列


下一篇:PAT 1021 个位数统计 C语言实现