Cod sursa(job #99791)

Utilizator gurneySachelarie Bogdan gurney Data 11 noiembrie 2007 16:27:21
Problema Zvon Scor 0
Compilator fpc Status done
Runda Happy Coding 2007 Marime 2.75 kb
program zvon;
  const
    fin='zvon.in';
    fout='zvon.out';
    nmax=100200;
  var
    f1,f2:text;
    prev,start,target,s2,t2:array[1..nmax] of longint;
    time,crt,st,down,last:array[1..nmax] of longint;
    ist,i,j,x,y,t,it,n,m,ne,maxtime:longint;
    frunza:array[1..nmax] of boolean;

procedure insert(x,y:longint);
  begin
    inc(ne);
    start[ne]:=x;target[ne]:=y;
    prev[ne]:=last[x];
    last[x]:=ne;
  end;

procedure qsort(st,dr:longint);
  var
    i,j:longint;
    x,tmp:longint;
  begin
    i:=st;j:=dr;
    x:=down[t2[(st+dr)shr 1]];
    repeat
      while down[t2[i]]<x do inc(i);
      while down[t2[j]]>x do dec(j);
      if i<=j then
        begin
          tmp:=t2[i];t2[i]:=t2[j];t2[j]:=tmp;
          tmp:=s2[i];s2[i]:=s2[j];s2[j]:=tmp;
          inc(i);dec(j);
        end;
    until i>j;
    if j>st then qsort(st,j);
    if i<dr then qsort(i,dr);
  end;

begin
  assign(f1,fin);
  assign(f2,fout);
    reset(f1);
    rewrite(f2);
    readln(f1,t);
    for it:=1 to t do
      begin
        readln(f1,n);
        ne:=0;
        fillchar(down,sizeof(down),0);
        for i:=1 to n-1 do
          begin
            readln(f1,x,y);
            insert(x,y);
            frunza[x]:=false;
          end;
        st[1]:=1;ist:=1;
        while ist>0 do
          begin
            x:=st[ist];
            y:=last[x];
            if y<>0 then
              begin
                inc(ist);
                st[ist]:=target[y];
                last[x]:=prev[y];
              end
            else
              begin
                if frunza[x] then
                  down[x]:=1;
                dec(ist);
                if ist>0 then
                  if down[st[ist]]<down[x]+1 then
                    down[st[ist]]:=down[x]+1;
              end;
          end;
        for i:=1 to n do
          if frunza[i]=false then
            inc(down[i])
          else
            frunza[i]:=false;
        for i:=1 to ne do
          begin
            s2[i]:=start[i];t2[i]:=target[i];
          end;
        qsort(1,ne);
        x:=ne;
        ne:=0;
        for i:=1 to x do
          insert(s2[i],t2[i]);
        st[1]:=1;ist:=1;time[1]:=0;
        maxtime:=0;
        while ist>0 do
          begin
            x:=st[ist];
            if time[x]>maxtime then
              maxtime:=time[x];
            y:=last[x];
            if y<>0 then
              begin
                inc(ist);
                st[ist]:=target[y];
                time[st[ist]]:=time[x]+1;
                inc(time[x]);
                last[x]:=prev[y];
              end
            else
              dec(ist);
          end;
        writeln(f2,maxtime);
      end;
  close(f2);
  close(f1);
end.