Cod sursa(job #106180)

Utilizator cos_minBondane Cosmin cos_min Data 18 noiembrie 2007 13:59:19
Problema Zvon Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 2.32 kb
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;

#define in "zvon.in"
#define out "zvon.out"
#define dim 100067

int T, N, Q;
int Vec[dim];
bool Sel[dim], Selq[dim];
vector< vector<int> > L;

struct Compare {
       bool operator() (int i, int j)
       {
            return Vec[i] > Vec[j];
       }
};

void DF(int);
void Solve(int,int);
void Qsort(int,int,int);

int main()
{
    int X, Y;
    
    freopen(in,"r",stdin);
    freopen(out,"w",stdout);
    
    scanf("%d", &T);
    for ( ; T > 0; T-- )
    {
        scanf("%d", &N);
        L.clear(); L.resize(N+1);
        
        memset(Sel,0,sizeof(Sel)); memset(Selq,0,sizeof(Selq)); memset(Vec,0,sizeof(Vec));
        
        for ( int i = 1; i < N; i++ ) L[i].push_back(0);
        
        for ( int i = 1; i < N; i++ )
        {
            scanf("%d%d", &X, &Y);
            L[X].push_back(Y);
        }
        
        DF(1);
        
        for ( int i = 1; i <= N; i++ )
            if ( L[i].size() > 1 ) Qsort( 1, L[i].size()-1, i);
        
        Q = 0;
        Solve(1,0);
        
        printf("%d\n", Q);
    }
}

void Qsort(int st, int dr, int nod)
{
     int i = st-1, j = dr, pivot = Vec[L[nod][st]];
     
     while ( i <= j )
     {
           do { i++; } while ( Vec[L[nod][i]] < pivot && i <= dr );
           do { j--; } while ( Vec[L[nod][j]] > pivot && j >= 1 );
           
           if ( i < j )
           {
                int aux = L[nod][i];
                L[nod][i] = L[nod][j];
                L[nod][j] = aux;
                
                //swap(L[nod][i],L[nod][j]);
           }
     }
     
     if ( st < j ) Qsort(st,j,nod);
     if ( i < dr ) Qsort(i,dr,nod);   
}

void DF(int nod)
{
     Sel[nod] = 1;
     
     if ( L[nod].size() == 1 ) Vec[nod] = 0; 
     
     for ( int i = 1; i < L[nod].size(); i++ )
     {
         int j = L[nod][i];
         if ( !Sel[j] )
         {
              DF(j);
              
              Vec[nod] = Vec[nod] + Vec[j] + 1;
         }
     }
}

void Solve(int nod, int timp)
{
     Selq[nod] = 1;
     
     if ( Q < timp ) Q = timp;
     
     for ( int i = 1; i < L[nod].size(); i++ )
     {
         int j = L[nod][i];
         
         if ( !Selq[j] ) Solve(j,timp+i);
     }
}