Cod sursa(job #106470)

Utilizator cos_minBondane Cosmin cos_min Data 18 noiembrie 2007 17:34:27
Problema Zvon Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 1.98 kb
#include <stdio.h>
#include <fstream>
#include <vector>
using namespace std;

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

int T, N, M;
int gasit, size=1, act_size=1, k;
int Vec[dim], list[dim], S[dim];
bool Sel[dim];
vector<int> L[dim];

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

void DF(int);

int main()
{
    int X, Y;
    int maxim, poz;
    freopen(in,"r",stdin);
    freopen(out,"w",stdout);
    
    scanf("%d", &T);
    for ( ; T > 0; T-- )
    {
        scanf("%d", &N);
        
        memset(Sel,0,sizeof(Sel));
        memset(Vec,0,sizeof(Vec));
        
        for ( int i = 1; i <= N; i++ ) L[i].clear(), S[i] = Sel[i] = 0;
        
        if ( N == 1 ) 
        {
             printf("0\n");
             continue;
        }
        
        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++ )
            sort(L[i].begin(), L[i].end(), Compare() );
        
        size=1;
        
        list[size] = 1;
        act_size = 1;
        M = N;
        int Q = 0;
        
        while ( M )
        {
              for ( int i = 1; i <= act_size; i++ )
              {
                  k = list[i];
                  
                  if ( Sel[k] == 1 ) continue;
                  
                  if ( S[k] >= L[k].size() ) M -= 1, Sel[k] = 1; 
                  else size++, list[size] = L[k][S[k]];
                  
                  S[k]++;
              }
              
              act_size = size;
              
              if ( M > 0 ) Q++;
        }
        
        printf("%d\n", Q);
    }
}

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