Cod sursa(job #44156)

Utilizator cimiCristina Stancu-Mara cimi Data 30 martie 2007 22:02:11
Problema Mese Scor 100
Compilator fpc Status done
Runda Arhiva de probleme Marime 2 kb
const
  lim=100005;
var
  a:array[1..lim,1..2] of longint;
  fii,mese,sum,st:array[0..lim] of longint;
  i,j,n,m,s,rad,dad:longint;

procedure Sort(l, r: longint);
var
  i, j, x, y: longint;
begin
  i := l; j := r; x := a[(l+r) DIV 2,1];
  repeat
    while a[i,1] < x do i := i + 1;
    while x < a[j,1] do j := j - 1;
    if i <= j then
    begin
      y := a[i,1]; a[i,1] := a[j,1]; a[j,1] := y;
      y := a[i,2]; a[i,2] := a[j,2]; a[j,2] := y;
      i := i + 1; j := j - 1;
    end;
  until i > j;
  if l < j then Sort(l, j);
  if i < r then Sort(i, r);
end;

procedure Sortf(l, r: longint);
var
  i, j, x, y: longint;
begin
  i := l; j := r; x := sum[fii[(l+r) DIV 2]];
  repeat
    while sum[fii[i]] < x do i := i + 1;
    while x < sum[fii[j]] do j := j - 1;
    if i <= j then
    begin
      y := fii[i]; fii[i] := fii[j]; fii[j] := y;
      i := i + 1; j := j - 1;
    end;
  until i > j;
  if l < j then Sortf(l, j);
  if i < r then Sortf(i, r);
end;

procedure doit(x:longint);
var
  i:longint;
begin
  mese[x]:=1;
  for i:=st[x] to st[x+1]-1 do
    doit(a[i,2]);
  j:=0;
  for i:=st[x] to st[x+1]-1 do
  begin
    inc(j);
    fii[j]:=a[i,2];
  end;
  sortf(1,j);
  i:=1;
  while (i<=j) and (sum[x]+sum[fii[i]]<=s) do
  begin
    sum[x]:=sum[x]+sum[fii[i]];
    mese[x]:=mese[x]+mese[fii[i]]-1;
    inc(i);
  end;
  while i<=j do
  begin
    mese[x]:=mese[x]+mese[fii[i]];
    inc(i);
  end;
end;

begin
  assign(input,'mese.in');
  reset(input);
  readln(n,s);
  j:=0;
  for i:=1 to n do
  begin
    readln(dad,sum[i]);
    if dad=0
      then rad:=i
      else
      begin
        inc(j);
        a[j,1]:=dad;
        a[j,2]:=i;
      end;
  end;
  sort(1,j);
  close(input);
  st[n+1]:=n;
  for i:= n-2 downto 0 do
    if a[i,1]<>a[i+1,1] then st[a[i+1,1]]:=i+1;
  for i:=n downto 1 do
    if st[i]=0 then st[i]:=st[i+1];
  doit(rad);
  assign(output,'mese.out');
  rewrite(output);
  writeln(mese[rad]);
  close(output);
end.