题面:
思路:
二分高度差,bfs
代码:
var mid,l,r,i,j,ans,tot,head,tail,n,sum:longint;
f:array[0..505,0..505] of boolean;
q:array[0..500005,0..3] of longint;
dx,dy:array[0..3] of longint;
a:array[0..505,0..505] of longint;
function pd(x,y:longint):boolean;
begin
exit((x>=1) and (x<=n) and (y>=1) and (y<=n));
end;
function bfs(x,y,z:longint):boolean;
var i,l,p:longint;
begin
sum:=1;head:=1;tail:=1;q[1,1]:=x;q[1,2]:=y;f[x,y]:=true;
while (head<=tail) do
begin
for i:=0 to 3 do
begin
l:=q[head,1]+dx[i]; p:=q[head,2]+dy[i];
if not pd(l,p) then continue;
if f[l,p] then continue;
if abs(a[l,p]-a[q[head,1],q[head,2]])>z then continue;
inc(sum); f[l,p]:=true;
inc(tail);
q[tail,1]:=l; q[tail,2]:=p;
end;
inc(head);
end;
exit(sum>=tot);
end;
function check(x:longint):boolean;
var i,j:longint;
begin
fillchar(f,sizeof(f),false);
for i:=1 to n do
for j:=1 to n do
if not f[i,j] then
if bfs(i,j,x) then exit(true);
exit(false);
end;
begin
assign(input,'tractor.in');
reset(input);
assign(output,'tractor.out');
rewrite(output);
dx[0]:=0; dx[1]:=1; dx[2]:=0; dx[3]:=-1;
dy[0]:=1; dy[1]:=0; dy[2]:=-1; dy[3]:=0;
read(n);
for i:=1 to n do for j:=1 to n do read(a[i,j]);
if n mod 2=1 then tot:=n*n div 2+1 else tot:=n*n div 2;
l:=0; r:=1000000;
while (l<=r) do
begin
mid:=(l+r) div 2;
if (check(mid)) then begin ans:=mid; r:=mid-1; end else l:=mid+1;
end;
writeln(ans);
close(input);close(output);
end.