Pagini recente » Profil melaniaspoiala | Profil agarici | Profil Stefan0812 | Cod sursa (job #1331) | Cod sursa (job #157436)
Cod sursa(job #157436)
# include <stdio.h>
# include <values.h>
typedef struct nod {
long key;
nod *next;
};
nod *a[100010];
long n, grad[100010];
void calc (long n, long p)
{
if ( a[n] == NULL )
grad[n] = 0;
else
{
long nr = p;
for ( nod *q = a[n]; q; q=q->next )
{
calc ( q->key, nr );
grad[++nr] = grad[q->key];
}
long mij ,i,j,aux,st=p+1,dr=nr;
int ok=1;
while (ok)
{
i = st; j = dr;
ok = 0; mij = (dr + st )/2;
do
{
while ( grad[i] < grad[mij] ) ++i;
while ( grad[j] > grad[mij] ) --j;
if ( i <= j )
{
aux = grad[i];
grad[i] = grad[j];
grad[j] = aux;
++i;--j;
}
}
while ( i < j );
if ( st < j )
{
dr = j;
ok = 1;
}
if ( dr > i )
{
st = i;
ok = 1;
}
}
long maxim = 0;
for ( i = p+1; i <= nr; ++ i )
if ( maxim < grad[i]+nr-i+1 )
maxim = grad[i]+nr-i+1;
grad[n] = maxim;
}
}
void add ( long x, long y )
{
nod *p;
p = new nod;
p->key = y;
p->next = a[x];
a[x] = p;
}
void cit ()
{
int t;
freopen ( "zvon.in", "r", stdin ); freopen ( "zvon.out", "w", stdout );
scanf ( "%d", &t );
for ( int i = 0; i < t; ++ i )
{
scanf ( "%ld", &n );
if ( n <= 1 )
printf ( "0\n" );
else
{ long x,y;
for ( long j = 0; j < n-1; ++ j )
{
scanf ( "%ld %ld", &x, &y );
add ( x, y );
}
calc(1, -1);
printf ( "%ld\n", grad[1] );
}
for ( long k = 0; k < n; ++ k )
a[k] = NULL;
}
fclose ( stdout ); fclose ( stdin );
}
int main ()
{
cit ();
return 0;
}