第四题满分算法:
var w,r,minn,i,j,n,m:longint;
c:array[0..16] of longint;
a,b,s,f:array[0..16,0..16] of longint;
function min(x,y:longint):longint;
begin
if x>y then exit(y) else exit(x);
end;
procedure dp;
var i,sum,j,k:longint;
begin
fillchar(s,sizeof(s),0);
for i:=1 to m do
for j:=1 to i do
begin
for k:=1 to r do s[i,j]:=s[i,j]+abs(b[k,i]-b[k,j]);
for k:=1 to r-1 do s[i,j]:=s[i,j]+abs(b[k,i]-b[k+1,i]);
end;
fillchar(f,sizeof(f),12);
for i:=1 to m do f[1,i]:=s[i,i];
for i:=2 to w do
for j:=i to m-w+i do
for k:=i-1 to j-1 do
f[i,j]:=min(f[i,j],f[i-1,k]+s[j,k]);
for i:=w to m do
minn:=min(minn,f[w,i])
end;
procedure dfsr(x,s:longint);
var i:longint;
begin
if s=r then
begin
dp;
exit;
end;
if x=n+1 then exit;
for i:=0 to 1 do
begin
if i=1 then b[s+1]:=a[x];
dfsr(x+1,s+i);
end;
end;
begin
assign(input,'submatrix.in');
reset(input);
assign(output,'submatrix.out');
rewrite(output);
readln(n,m,r,w);
for i:=1 to n do
for j:=1 to m do read(a[i,j]);
minn:=maxlongint;
dfsr(1,0);
writeln(minn);
close(input);
close(output);
end.