# BZOJ 1564 :[NOI2009]二叉查找树（树型DP）

二叉查找树

【题目描述】

【输入格式】

【输出格式】

【样例输入】

4 10

1 2 3 4

1 2 3 4

1 2 3 4

【样例输出】

29

program treap;
var
f:array[0..100,0..100,0..100]of longint;
a:array[1..3,0..100]of longint;
s:array[0..100,0..100]of longint;
n,i,m,j,w,k:longint;
function min(x,y:longint):longint;
begin
if x<y then min:=x else min:=y;
end;
procedure sort(x:longint);
var i,j,t:longint;
begin
for i:=1 to n-1 do
for j:=i+1 to n do
if a[x,i]>a[x,j] then
begin
t:=a[1,i]; a[1,i]:=a[1,j]; a[1,j]:=t;
t:=a[2,i]; a[2,i]:=a[2,j]; a[2,j]:=t;
t:=a[3,i]; a[3,i]:=a[3,j]; a[3,j]:=t;
end;
end;
begin
assign(input,'treap.in');
reset(input);
assign(output,'treap.out');
rewrite(output);
for i:=1 to n do
for i:=1 to n do
for i:=1 to n do
sort(2);
for i:=1 to n do
a[2,i]:=i;
sort(1);
for i:=1 to n do
for j:=i to n do
s[i,j]:=s[i,j-1]+a[3,j];
for i:=1 to n do
for j:=1 to n do
for w:=1 to n do
f[i,j,w]:=maxlongint div 10;
for i:=1 to n+1 do
for w:=0 to n do
f[i,i-1,w]:=0;
for w:=n downto 1 do
for i:=n downto 1 do
for j:=i to n do
for k:=i to j do
if i=j then
if a[2,k]>=w then f[i,j,w]:=a[3,k] else f[i,j,w]:=a[3,k]+m
else begin
if a[2,k]>=w then f[i,j,w]:=min(f[i,j,w],f[i,k-1,a[2,k]]+f[k+1,j,a[2,k]]+s[i,j]);
f[i,j,w]:=min(f[i,j,w],f[i,k-1,w]+f[k+1,j,w]+s[i,j]+m);
end;
writeln(f[1,n,1]);
close(input); close(output);
end.
View Code

posted @ 2015-02-10 12:18  QTY_YTQ  阅读(275)  评论(0编辑  收藏  举报