Cod sursa(job #102750)

Utilizator georgianaGane Andreea georgiana Data 14 noiembrie 2007 18:00:00
Problema Zvon Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 2.16 kb
#include <stdio.h>
#include <stdlib.h>

#define Nmax 100001
#define inf 1000001
struct nod{
              int nod;
              struct nod *urm;
          };
          
struct nod *v[Nmax],*p;
int nt,n,x,y,dh,mi,t[Nmax],h[Nmax];

void insert(int x)
{
     dh++;
     int i=dh;
     while (i>1 && h[i/2]<x) i/=2;
     h[i]=x;
}

int extr()
{
    h[0]=h[1];
    h[1]=h[dh];
    dh--;
    int i=1;
    do
    {
        int maxi=h[i];
        if (2*i<=dh && maxi<h[2*i]) maxi=h[2*i];
        if (2*i+1<=dh && maxi<h[2*i+1]) maxi=h[2*i+1];
        if (maxi==h[i]) break;
        if (maxi==h[2*i]) h[2*i]=h[i],h[i]=maxi,i*=2; 
        else if (maxi==h[2*i+1]) h[2*i+1]=h[i],h[i]=maxi,i=2*i+1; 
    }while(1);
    return h[0];
}

int max(int i, int j)
{
    if (i>j) return i;
    return j;
}

void df(int k)
{
     t[k]=0;
     struct nod* p;
     p=v[k];
     while (p!=NULL)
     {
           df(p->nod);
           p=p->urm;
     }     
     dh=0;
     p=v[k];
     while (p!=NULL)
     {
           insert(t[p->nod]);
           p=p->urm;
     }
     mi=0;
     while (dh>0)
         {
             x=extr();
             mi++;
             t[k]=max(t[k],x+mi);
         }
}

void freee(struct nod* p)
{
     if (p->urm!=NULL)
     {
         freee(p->urm);
         free(p->urm);
     }
}

int main()
{
    freopen("zvon.in","r",stdin);
    freopen("zvon.out","w",stdout);
    scanf("%d",&nt);

    while (nt--)
    {
          scanf("%d",&n);
          for (int i=1;i<=n;i++) { v[i]=NULL; t[i]=0; }
          for (int i=1;i<n;i++)
             {
                   scanf("%d %d",&y,&x);
                   t[x]=1;
                   p=(struct nod*)malloc(sizeof(struct nod));
                   p->nod=x;
                   p->urm=v[y];
                   v[y]=p;
             }
          int i=1;
          while (i<=n && t[i]==1) i++;          
          if (i<=n) df(i);
          printf("%d\n",t[i]);
          for (int i=1;i<=n;i++)
              if (v[i]!=NULL)
                 {
                     freee(v[i]);
                     free(v[i]);
                 }
    }
    return 0;
}