Cod sursa(job #104363)

Utilizator vanila_CPPIonescu Victor Cristian vanila_CPP Data 16 noiembrie 2007 01:20:17
Problema Zvon Scor 100
Compilator cpp Status done
Runda Happy Coding 2007 Marime 2.28 kb
#include <cstdio>
#include <algorithm>
using namespace std;
struct lista {
    long inf;
    lista *urm;
} *v[100001];
long rez[100001],poz[100001],grad[100001];
long n,t,dim;

void files_open(void){
    freopen("zvon.in","rt",stdin);
    freopen("zvon.out","wt",stdout);
    scanf("%ld",&t);
}

void files_close(void){
    fclose(stdin);
    fclose(stdout);
}

void citire(void){
    long i,x,y;
    lista *q;
    scanf("%ld",&n);
    for (i=1;i<=n;i++){
    v[i]=NULL;
    }
    for (i=1;i<n;i++){
        scanf("%ld%ld",&x,&y);
        q=new lista;
        q->inf=y;
        q->urm=v[x];
        v[x]=q;
    };
}


void df(long x){
    long i,max=0;
    lista *q;
    if (v[x]==NULL){
        grad[x]=0;
    } else{
        for (q=v[x];q;q=q->urm){
            df(q->inf);
            if (grad[q->inf]>max){
                max=grad[q->inf];
            }
        }
        grad[x]=max+1;
    }
}


void repair(long i){
    long l,r,aux,max;
    l=2*i;
    r=l+1;
    max=i;
    if ((l<=dim)&&(grad[l]>grad[max])){
        max=l;
    }
    if ((r<=dim)&&(grad[r]>grad[max])){
        max=r;
    }
    if (max!=i) {
        aux=grad[i];
        grad[i]=grad[max];
        grad[max]=aux;
        aux=poz[i];
        poz[i]=poz[max];
        poz[max]=aux;
        repair(max);
    }
}

void build_heap(void){
    long i;
    for (i=n/2;i>=1;i--){
        repair(i);
    }
}

void heapsort(void){
    long i;
    long aux;
    build_heap();
    for (i=n;i>=2;i--){
        aux=grad[1];
        grad[1]=grad[i];
        grad[i]=aux;
        aux=poz[1];
        poz[1]=poz[i];
        poz[i]=aux;
        dim--;
        repair(1);
    }
}


long max(long x,long y){
        if (x>y){return x;} else {
        return y;
       }
}

void prel(long x){
    long vec[100001];
    long lun=0,sum,i,rest;
    lista *q;
    for (q=v[x];q;q=q->urm){
        vec[++lun]=rez[q->inf];
    }
    sort(vec+1,vec+lun+1);
    rez[x]=0;
    for (i=lun,rest=1,sum=0;i>=1;rest++,i--){
        rez[x]=max(rez[x],vec[i]+rest);
    };
}



void prelu(void){
    long i;
    for (i=1;i<=n;poz[i]=i,i++);
    df(1);
    dim=n;
    heapsort();
    for (i=1;i<=n;i++){
        prel(poz[i]);
    }
    printf("%ld\n",rez[1]);
}

int main(void){
    long i;
    files_open();
    for (i=1;i<=t;i++){
        citire();
        prelu();
    }
    files_close();
}