算法:TreeDP
分析:直接将3-21的模型套用过来,只有一点不同的是由原先的树型变成了直线型,实际上变得更加简单了,不用再分成两棵子树。
在递归的时候直接加个判断以防止跳出边界就行了。
program ksaw;
const
maxn=1000;
maxm=50;
var
n,m:longint;
w:array [0..maxn] of longint;
d:array [0..maxn,0..maxn] of longint;
f:array [-1..maxn,-1..maxn,-1..maxm] of longint;
procedure init;
var
i,j:longint;
begin
fillchar(d,sizeof(d),100);
fillchar(f,sizeof(f),100);
readln(n,m);
for i:=n downto 1 do readln(w[i],d[i,i-1]);
for i:=0 to n-1 do for j:=i+2 to n do d[j,i]:=d[j-1,i]+d[j,j-1];
end;
function min(x,y:longint):longint;
begin
if x<y then exit(x) else exit(y);
end;
function dp(st,ed,build:longint):longint;
var
i,temp:longint;
begin
if f[st,ed,build]<f[-1,-1,-1] then exit(f[st,ed,build]);
for i:=0 to build do
begin
temp:=0;
if st<n then inc(temp,dp(st+1,ed,build));
inc(temp,d[st,ed]*w[st]);
f[st,ed,build]:=min(f[st,ed,build],temp);
end;
for i:=0 to build-1 do
begin
temp:=0;
if st<n then inc(temp,dp(st+1,st,build-1));
f[st,ed,build]:=min(f[st,ed,build],temp);
end;
exit(f[st,ed,build]);
end;
begin
assign(input,'ksaw.in'); reset(input);
assign(output,'ksaw.out'); rewrite(output);
init;
writeln(dp(0,0,m));
close(input); close(output);
end.