Cod sursa(job #1471555)

Utilizator bogdan10bosBogdan Sitaru bogdan10bos Data 14 august 2015 13:06:13
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>

#define INF ( (1 << 30) - 1 + (1 << 30) )
#define mod 666013

using namespace std;
int n, x, y, start, mx, i, l[100005];
vector <int> mch[100005];
vector <int> :: iterator it;
queue <int> q;
int main()
{
    freopen("darb.in", "r", stdin);
    freopen("darb.out", "w", stdout);

    scanf("%d", &n);
    for(i = 1; i < n; i++)
    {
        scanf("%d%d", &x, &y);
        mch[x].push_back(y);
        mch[y].push_back(x);
    }

    q.push(1);
    l[1] = 1;
    start = 0;
    while(!q.empty())
    {
        x = q.front();
        q.pop();

        if(l[x] > l[start])
            start = x;

        for(it = mch[x].begin(); it != mch[x].end(); it++)
        {
            y = *it;
            if(!l[y])
            {
                l[y] = l[x] + 1;
                q.push(y);
            }
        }
    }

    for(i = 1; i <= n; i++)
        l[i] = 0;

    q.push(start);
    l[start] = 1;
    mx = 0;
    while(!q.empty())
    {
        x = q.front();
        q.pop();

        if(l[x] > mx)
            mx = l[x];

        for(it = mch[x].begin(); it != mch[x].end(); it++)
        {
            y = *it;
            if(!l[y])
            {
                l[y] = l[x] + 1;
                q.push(y);
            }
        }
    }

    printf("%d", mx);
    return 0;
}