Cod sursa(job #1890344)

Utilizator tudorgalatanRoman Tudor tudorgalatan Data 23 februarie 2017 11:05:40
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream fin ("darb.in");
ofstream fout ("darb.out");

unsigned int N;
unsigned int a, b;

vector <unsigned int> G[100001];
queue <unsigned int> Q;
bool seen[100001];
unsigned int node;
unsigned int i;

unsigned int sol[100001];

int main ()
{
    /// READ
    fin >> N;
    for (i=1; i<=N-1; i++)
    {
        fin >> a >> b;
        G[a].push_back(b);
        G[b].push_back(a);
    }

    /// SOLVE
    sol[1] = 1;                                     /// First BFS
    seen[1] = 1;
    Q.push(1);
    while (!Q.empty())
    {
        node = Q.front();
        Q.pop();
        seen[node] = 1;
        for (i=0; i<G[node].size(); i++)
            if (!seen[G[node][i]])
            {
                seen[G[node][i]] = 1;
                sol[G[node][i]] = sol[node] + 1;
                Q.push(G[node][i]);
            }
    }
    sol[node] = 1;                                  /// Second BFS
    seen[node] = 0;
    Q.push(node);
    while (!Q.empty())
    {
        node = Q.front();
        Q.pop();
        seen[node] = 0;
        for (i=0; i<G[node].size(); i++)
            if (seen[G[node][i]] == 1)
            {
                seen[G[node][i]] = 0;
                sol[G[node][i]] = sol[node] + 1;
                Q.push(G[node][i]);
            }
    }

    /// PRINT
    fout << sol[node];
    return 0;
}