Cod sursa(job #106478)

Utilizator cos_minBondane Cosmin cos_min Data 18 noiembrie 2007 17:44:27
Problema Zvon Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 2.15 kb
#include <stdio.h>
#include <fstream>
#include <vector>
#include <set>
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];

set<int> R;
set<int>::iterator it;

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));
        
        
        R.clear();
        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;
        R.insert(1);
        M = N;
        int Q = 0, poz;
        
        while ( M )
        {
              size = 0;
              poz = 0;
              
              for ( it = R.begin(); it != R.end(); it++ )
                  size++, list[size] = *it;
              
              for ( poz = 1; poz <= size; poz++ )
              {
                  k = list[poz];
                  
                  if ( S[k] >= L[k].size() ) M -= 1, R.erase(k); 
                  else R.insert( L[k][S[k]] );
                  
                  S[k]++;
              }
              
              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;
}