STILL WA!!HELP!!
Posted by
yuri 1 Jun 2004 10:30
program ural1018;
var
n,q,i,j,s,t:longint;
link:array[1..100,1..100]of integer;
f:array[0..100,0..100]of longint;
lc,rc,num:array[0..100]of longint;
rec:array[0..100,1..3]of longint;
app:array[0..100]of longint;
sum:array[0..100]of longint;
procedure tree(k,ff:longint);
var
i:longint;
begin
for i:=1 to num[k] do
if rec[k,i]<>ff then
if lc[k]<>0 then rc[k]:=rec[k,i] else lc[k]:=rec[k,i];
if lc[k]<>0 then tree(lc[k],k);
if rc[k]<>0 then tree(rc[k],k);
end;
function jisuan(k:longint):longint;
var
tot,tot1:longint;
begin
if lc[k]=0 then begin jisuan:=0;exit;end;
tot:=0;tot1:=0;
if lc[k]<>0 then begin inc(tot,1+jisuan(lc[k]));inc(tot1,sum[lc[k]]+link[k,lc[k]]);end;
if rc[k]<>0 then begin inc(tot,1+jisuan(rc[k]));inc(tot1,sum[rc[k]]+link[k,rc[k]]);end;
jisuan:=tot;
app[k]:=tot;
sum[k]:=tot1;
end;
function cal(k,q:longint):longint;
var
p,max:longint;
begin
if f[k,q]<>-1 then begin cal:=f[k,q];exit;end;
if q=0 then begin cal:=0;f[k,q]:=0;exit;end;
if lc[k]=0 then begin cal:=0;f[k,q]:=0;exit;end;
if (q=app[k]) then begin cal:=sum[k];f[k,q]:=sum[k];exit;end;
max:=-1;
if (rc[k]<>0)and(app[rc[k]]>=q-1) then begin
p:=cal(rc[k],q-1)+link[k,rc[k]];
if p>max then max:=p;
end;
if (lc[k]<>0)and(app[lc[k]]>=q-1) then begin
p:=cal(lc[k],q-1)+link[k,lc[k]];
if p>max then max:=p;
end;
if rc[k]<>0 then begin
for i:=0 to q-2 do
if (app[lc[k]]>=i)and(app[rc[k]]>=q-2-i) then begin
p:=cal(lc[k],i)+cal(rc[k],q-2-i)+link[k,rc[k]]+link[k,lc[k]];
if p>max then max:=p;
end;
end;
cal:=max;
f[k,q]:=max;
end;
begin
read(n,q);
fillchar(sum,sizeof(sum),0);
fillchar(num,sizeof(num),0);
fillchar(rec,sizeof(rec),0);
fillchar(lc,sizeof(lc),0);
fillchar(rc,sizeof(rc),0);
fillchar(app,sizeof(app),0);
for i:=1 to n-1 do
begin
read(s,t,link[s,t]);
link[t,s]:=link[s,t];
if link[s,t]=0 then begin dec(q);continue;end;
inc(num[s]);rec[s,num[s]]:=t;
inc(num[t]);rec[t,num[t]]:=s;
end;
for i:=1 to n do
for j:=0 to n do
f[i,j]:=-1;
tree(1,0);
app[1]:=jisuan(1);
if q<=0 then begin writeln(0);halt;end;
if n=q then begin writeln(sum[1]);halt;end;
writeln(cal(1,q));
end.