Cod sursa(job #128034)

Utilizator Data 25 ianuarie 2008 22:21:36
Problema Zvon Scor 0
Compilator fpc Status done
Runda Arhiva de probleme Marime 2.9 kb
type pelem=^elem;
     elem=record
       info:longint;
       next:pelem;
     end;
var fi,fo:text;
    n,i,j,t,max,v1,v2,nm,ct,vl,valo,k:longint;
    tati,nivel:array[1..100000]of pelem;
    tmin,niv,fii:array[1..100000]of longint;
procedure heapsort(n:longint);
var i,j,k:longint;
    aux:longint;
begin
     for i:=1 to n do
         begin
              j:=i;
              while (j shr 1<>0) and (fii[j shr 1]>fii[j]) do
                    begin
                         aux:=fii[j shr 1]; fii[j shr 1]:=fii[j]; fii[j]:=aux;
                         j:=j shr 1; end;
         end;
     i:=n;
     while i>1 do
           begin
                aux:=fii[1]; fii[1]:=fii[i]; fii[i]:=aux;
                dec(i); j:=1;
                while (j>0) do
                   begin
                        k:=2*j;
                        if (k>i) then  break;
                        if (k+1<=i) and (fii[k+1]<fii[k]) then inc(k);
                        if fii[j]<=fii[k] then break;
                        aux:=fii[j]; fii[j]:=fii[k]; fii[k]:=aux; j:=k;
                   end;
           end;
end;
function part(st,dr:longint):longint;
var i,j,s,aux:longint;
begin
  i:=st; j:=dr; s:=-1;
  while i<j do
    begin
      if fii[i]<fii[j] then
        begin
          aux:=fii[i];
          fii[i]:=fii[j];
          fii[j]:=aux;
          s:=-s;
        end;
      if s=1 then inc(i)
             else dec(j);
    end;
  part:=i;
end;
procedure qsort(st,dr:longint);
var p:longint;
begin
  if st<dr then
    begin
      p:=part(st,dr);
      qsort(st,p-1);
      qsort(p+1,dr);
    end;
end;
procedure qin(var first:pelem; vl:longint);
var p:pelem;
begin
  new(p);
  p^.info:=vl;
  p^.next:=first;
  first:=p;
end;
procedure qout(var first:pelem; var vl:longint);
var p:pelem;
begin
  vl:=first^.info;
  p:=first;
  first:=first^.next;
  dispose(p);
end;
procedure solv;
begin
  read(fi,n);
  niv[1]:=1; nm:=0;
  qin(nivel[1],1);
  for i:=1 to n-1 do
    begin
      read(fi,v1,v2);
      qin(tati[v1],v2);
      niv[v2]:=niv[v1]+1;
      qin(nivel[niv[v2]],v2);
      if niv[v2]>nm then nm:=niv[v2];
    end;
  for i:=nm-1 downto 1 do
   begin
    while (nivel[i]<>nil) do
      begin
        qout(nivel[i],vl);
        ct:=0;
        while (tati[vl]<>nil) do
          begin
            qout(tati[vl],valo);
            inc(ct);
            fii[ct]:=tmin[valo];
          end;
        heapsort(ct);
        max:=-maxint;
        for j:=1 to ct do
          if fii[j]+j>max then max:=fii[j]+j;
        tmin[vl]:=max;
      end;
    end;
  writeln(fo,tmin[1]);
  for i:=1 to n do
    begin tmin[i]:=0; niv[i]:=0; end;
  for i:=1 to nm do
    while nivel[i]<>nil do qout(nivel[i],vl);
end;
begin
  assign(fi,'zvon.in'); reset(fi);
  assign(fo,'zvon.out'); rewrite(fo);
  read(fi,t);
  for k:=1 to t do
    solv;
  close(fi);
  close(fo);
end.