Cod sursa(job #1678839)

Utilizator hegedusPaul Hegedus hegedus Data 7 aprilie 2016 15:52:17
Problema Diametrul unui arbore Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <cstdio>
using namespace std;

const int nmax=100000;
int v[nmax],tata[nmax],n,x,y,i,j,q,k,p,cost;
bool viz[nmax];

void citire()
{
    freopen("darb.in","r",stdin);
    freopen("darb.out","w",stdout);
    scanf("%d",&n);
    for(x=1;x<=n;x++)
    {
        scanf("%d %d",&i,&j);
        tata[j]=i;
    }
}

int main()
{
    citire();

    v[1]=1; viz[1]=1;
    q=0; k=1; p=0;
    do
    {
        for(x=q+1;x<=q+k;x++)
        {
            for(y=1;y<=n;y++)
                if (tata[y]==v[x] && !viz[y])
                    viz[y]=1,
                    ++p,
                    v[q+k+p]=y;
        }
        q+=k; k=p; p=0;
    }while(k>0);

    for(x=1;x<=n;x++) viz[x]=0;

    v[1]=v[q]; viz[v[q]]=1;
    q=0; k=1; p=0;
    do
    {
        cost++;
        for(x=q+1;x<=q+k;x++)
        {
            for(y=1;y<=n;y++)
                if((y==tata[v[x]]||tata[y]==v[x])&&!viz[y])
                    viz[y]=1,
                    ++p,
                    v[q+k+p]=y;
        }
        q+=k; k=p; p=0;
    }while(k>0);

    printf("%d\n",cost);
    return 0;
}