Cod sursa(job #104184)

Utilizator Darth_NiculusIvan Nicolae Darth_Niculus Data 15 noiembrie 2007 23:12:08
Problema Zvon Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 2.14 kb
/* Ivan Nicolae - Bucuresti */
/* Happy Coding 2007 - Zvon */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NMAX 100001
#define _fin  "zvon.in"
#define _fout "zvon.out"

struct node
{
 int key;
 node *l;
};

int i,n,H[NMAX],Tp[NMAX],C[NMAX];
node* A[NMAX], *sf[NMAX];

void Insert(node*& R, node*& sf, int x)
{
 if (!R)
   {
    R=(node*)malloc(sizeof(node));
    R->key=x;
    R->l=0;
    sf=R;
   }
   else {
         node* xx=(node*)malloc(sizeof(node));
         xx->key=x;
         xx->l=0;
         sf->l=xx;
         sf=xx;
        }
}

void Df_h(int nod)
{
 int max=0;
 node* x=A[nod];
 while (x)
      {
       Df_h(x->key);
       if (H[x->key]>max)
         max=H[x->key];
       x=x->l;
      }
 H[nod]=1+max;
}

void Quick(int li, int ls, int A[])
{
 int i=li, j=ls, x=H[A[(li+ls)>>1]];
 while (i<=j)
      {
       while (H[A[i]]>x) i++;
       while (H[A[j]]<x) j--;
       if (i<=j)
         {
          int y=A[i]; A[i]=A[j]; A[j]=y;
          i++; j--;
         }
      }
 if (i<ls) Quick(i,ls,A);
 if (li<j) Quick(li,j,A);
}

void SortFii(node*& R)
{
 node*x = R;
 C[0]=0;
 while (x)
      {
       C[++C[0]]=x->key;
       x=x->l;
      }
 Quick(1,C[0],C);
 x=R; C[0]=0;
 while (x)
      {
       x->key=C[++C[0]];
       x=x->l;
      }
}

void Df_tmp(int nod)
{
// SortFii(A[nod]);
 node* x=A[nod];
 node* prev;
 if (x)
   {
    Tp[x->key]=1+Tp[nod];
    Df_tmp(x->key);
    prev=x;
    x=x->l;
   }
 while (x)
      {
       Tp[x->key]=1+Tp[prev->key];
       Df_tmp(x->key);
       prev=x;
       x=x->l;
      }
}

int main()
{
 freopen(_fin,"r",stdin);
 freopen(_fout,"w",stdout);

 int test=0;
 scanf("%d",&test);
 for (;test>=1;test--)
    {
 memset(A,NULL,sizeof(A));
 memset(H,0,sizeof(H));
 memset(Tp,0,sizeof(Tp));

 scanf("%d",&n);
 for (i=1;i<=n-1;i++)
    {
     int x,y;
     scanf("%d%d",&x,&y);
     Insert(A[x],sf[x],y);
    }

 Df_h(1);
 Df_tmp(1);

 int max=0;
 for (i=1;i<=n;i++)
    if (max<Tp[i])
      max=Tp[i];
 printf("%d\n",max);
    }
 fclose(stdin);
 fclose(stdout);
 return 0;
}