[二分答案] POJ2110 Mountain Walking
题目大意:
给你一个n×n的矩阵,让你找一条从(1,1)到(n,n)的一条路径,保证路径上经过点的最大值与最小值之差最小,输出这个差值。
题目分析:
典型的二分答案,枚举上下界区间,然后二分差值,求差值的最小值。
[pascal 代码]
CONST DX:ARRAY[1..4]OF -1..1=(0,0,1,-1); DY:ARRAY[1..4]OF -1..1=(-1,1,0,0); TYPE LZY=RECORD X,Y:LONGINT; END; VAR MAP:ARRAY[0..111,0..111]OF LONGINT; Q:ARRAY[0..100000]OF LZY; VIS:ARRAY[0..111,0..111]OF BOOLEAN; DOWN,UP,I,N,HEAD,TAIL,MIN,MAX,MINL:LONGINT; PROCEDURE INIT; VAR I,J:LONGINT; BEGIN READLN(N); MAX:=0; MIN:=MAXLONGINT; FOR I:=1 TO N DO BEGIN FOR J:=1 TO N DO BEGIN READ(MAP[I,J]); IF MAP[I,J]<MIN THEN MIN:=MAP[I,J]; IF MAP[I,J]>MAX THEN MAX:=MAP[I,J]; END; READLN; END; END; PROCEDURE INITQUE; BEGIN Q[1].X:=1; Q[1].Y:=1; VIS[1,1]:=TRUE; HEAD:=0;TAIL:=1; END; FUNCTION BFS(DOWN,UP:LONGINT):BOOLEAN; VAR I,J:LONGINT; PRE,TMP:LZY; BEGIN FILLCHAR(VIS,SIZEOF(VIS),FALSE); INITQUE; IF MAP[1,1]>UP THEN EXIT(FALSE); IF MAP[1,1]<DOWN THEN EXIT(FALSE); WHILE HEAD<TAIL DO BEGIN INC(HEAD); PRE:=Q[HEAD]; FOR I:=1 TO 4 DO BEGIN TMP.X:=PRE.X+DX[I]; TMP.Y:=PRE.Y+DY[I]; IF (TMP.X<1) OR (TMP.X>N) OR (TMP.Y<1) OR (TMP.Y>N) THEN CONTINUE; IF (MAP[TMP.X,TMP.Y]>=DOWN)AND(MAP[TMP.X,TMP.Y]<=UP)AND(NOT VIS[TMP.X,TMP.Y]) THEN BEGIN INC(TAIL); Q[TAIL]:=TMP; VIS[TMP.X,TMP.Y]:=TRUE; IF VIS[N,N] THEN EXIT(TRUE); END; END; END; EXIT(FALSE); END; PROCEDURE MAIN; VAR L,R,MID,I:LONGINT; BEGIN MINL:=MAXLONGINT; FOR I:=MIN TO MAX DO BEGIN L:=0;R:=MAX-MIN; WHILE L<R DO BEGIN MID:=(L+R)>>1; IF BFS(I,I+MID) THEN R:=MID ELSE L:=MID+1; END; IF L<MINL THEN MINL:=L; END; WRITELN(MINL); END; BEGIN INIT; MAIN; END.