ENG  RUSTimus Online Judge
Online Judge
Problems
Authors
Online contests
About Online Judge
Frequently asked questions
Site news
Webboard
Links
Problem set
Submit solution
Judge status
Guide
Register
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests
Rules
back to board

Discussion of Problem 1018. Binary Apple Tree

I used DP tree,but i got TLE on #9,who can help me
Posted by sxqqslf 23 Jul 2009 10:44
I used DP tree,but i got TLE on #9,who can help me?
Here is my program:

program ural1018;
var
  a,b,c,n,q,i,j:longint;
  l,r,tot:array[0..100] of longint;
  map,f:array[0..100,0..100] of longint;
  use:array[0..100] of boolean;
procedure setup(v:longint);
var
  i:longint;
begin
  for i:=1 to n do
  if (map[v,i]<>-1)and(not use[i]) then
  begin
    if l[v]=0 then l[v]:=i else
    if r[v]=0 then r[v]:=i;
    use[v]:=true;
    setup(i);
  end;
end;
procedure ready(v:longint);
begin
  if l[v]<>0 then begin inc(tot[v]);ready(l[v]);end;
  if r[v]<>0 then begin inc(tot[v]);ready(r[v]);end;
  tot[v]:=tot[v]+tot[l[v]]+tot[r[v]];
end;
procedure dp(v,q:longint);
var
  i,x:longint;
begin
  if q=0 then exit;
  if l[v]>0 then
  begin
    if (q-1<=tot[l[v]])and(q-1>=0) then
    dp(l[v],q-1);
    if f[v,q]<f[l[v],q-1]+map[l[v],v] then
    f[v,q]:=f[l[v],q-1]+map[l[v],v];
  end;
  if r[v]>0 then
  begin
    if (q-1<=tot[r[v]])and(q-1>=0) then
    dp(r[v],q-1);
    if f[v,q]<f[r[v],q-1]+map[v,r[v]] then
    f[v,q]:=f[r[v],q-1]+map[v,r[v]];
  end;
  if (l[v]>0)and(r[v]>0) then
  for i:=0 to q-2 do
  if (i<=tot[l[v]])and(q-i-2<=tot[r[v]])and(q-i-2>=0) then
  begin
    dp(l[v],i);
    dp(r[v],q-i-2);
    if f[v,q]<f[l[v],i]+f[r[v],q-i-2]+map[v,l[v]]+map[v,r[v]] then
    f[v,q]:=f[l[v],i]+f[r[v],q-i-2]+map[v,l[v]]+map[v,r[v]];
  end;
  if (l[v]=0)and(r[v]=0) then f[v,q]:=0;
end;
begin
  readln(n,q);if q>=n-1 then q:=n-1;
  for i:=1 to n do
  for j:=1 to n do map[i,j]:=-1;
  while not eof do
  begin
    read(a,b,c);
    map[a,b]:=c;
    map[b,a]:=c;
  end;
  setup(1);
  ready(1);
  dp(1,q);
  write(f[1,q]);
end.