Cod sursa(job #99746)

Utilizator gurneySachelarie Bogdan gurney Data 11 noiembrie 2007 15:57:54
Problema Zvon Scor 0
Compilator fpc Status done
Runda Happy Coding 2007 Marime 2.54 kb
program zvon;
  const
    fin='zvon.in';
    fout='zvon.out';
    nmax=100000;
  var
    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;

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