Cod sursa(job #1556815)

Utilizator mihai.constantinConstantin Mihai mihai.constantin Data 26 decembrie 2015 00:24:09
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int dmax = 100000;

int lst[dmax+1];
int vf[2*dmax + 1];
int urm[2*dmax + 1];
int nr;

int C[dmax+1];
int cost[dmax+1];

int N;

void adauga(int x, int y)
{
    nr++;
    vf[nr] = y;
    urm[nr] = lst[x];
    lst[x] = nr;
}

void BFS(int S)
{
    memset(cost, 0, sizeof(cost));

    int first, last, p, x, y;

    first = last = 1;

    //INSEREZ IN COADA NODUL S CU COSTUL 1
    C[1] = S; cost[S] = 1;

    while(first <= last)
    {
        x = C[first];

        //PARCURG VECINII y AI LUI x

        p = lst[x];

        while(p)
        {
            y = vf[p];

            if(cost[y] == 0)
            {
                last++;
                C[last] = y;
                cost[y] = 1 + cost[x];
            }

            p = urm[p];
        }

        first++;
    }
}

int main()
{
    freopen("darb.in", "r", stdin);
    freopen("darb.out", "w", stdout);

    int i, x, y, d_max, nod, diametru;

    scanf("%d", &N);
    for(i = 1; i < N; i++)
    {
        scanf("%d %d", &x, &y);

        adauga(x,y);
        adauga(y,x);
    }

    BFS(1);

    d_max = cost[1]; nod = 1;

    for(i = 2; i <= N; i++)
        if(d_max < cost[i])
        {
            d_max = cost[i];
            nod = i;
        }

    BFS(nod);

    diametru = cost[1];

    for(i = 2; i <= N; i++)
        if(diametru < cost[i]) diametru = cost[i];

    printf("%d", diametru);

    return 0;
}