您的位置:首页 > 其它

回家【推荐】

2016-07-15 19:42 246 查看
Description

  Alice住在森林里,森林可以看作是N*M的网格,森林里有怪兽,用‘.’表示空地,‘+’表示怪兽,‘V’表示Alice现在的位置,‘J’表示Alice的家。

  Alice可以从当前单元格向上下左右相邻单元格移动,有怪兽的地方也可以走,只不过比较危险,有怪兽的单元格对其他单元格会产生一定的危险系数,假设怪兽位置为(A,B),它对某单元格(R,C)的危险系数为:|R-A|+|C-B|,危险系数越小越危险,每个单元格的危险系数是所有怪兽对它产生的系数的最小值。

  Alice请你帮她找一条最佳路径回家,即使得路径上经过单元格的最小的危险系数最大。

Input

  输入第一行包含两个整数N和M(1<=N,M<=500),表示森林的大小。

  接下来N行每行包含M个字符:‘.’,‘+’,‘V’,‘J’。

  输入只包含一个‘V’和‘J’,而且至少有一个‘+’。

Output

  输出最佳路径中最小的危险系数。

Sample Input

输入1:

4 4

+...

....

....

V..J

输入2:

4 5

.....

+++.

.+.+.

V+.J+

Sample Output

输出1:

3

输出2:

0

 

分析:先预处理所以点的安全系数,然后二分枚举答案,进行计算即可。

 

const

 dx:array[1..4] of longint=(1,0,-1,0);

 dy:array[1..4] of longint=(0,1,0,-1);

var

 a:Array[1..500,1..500] of longint;

 g:array[1..500*500,1..3] of longint;

 n,m,i,ex,ey,sx,sy,mid:longint;

 flag:boolean;

 

procedure bfs;

 var l,r,head,tail,nextx,nexty,x,i,lll:longint;

    t:Array [1..500*500,1..2] of longint;

    b:array [1..500,1..500] of boolean;

begin

 head:=0; tail:=1;

 x:=mid;

 fillchar(b,sizeof(b),true);

 fillchar(t,sizeof(t),0);

 t[1,1]:=sx;t[1,2]:=sy;

 ifa[sx,sy]<x then exit;

 repeat

 inc(head);

  fori:=1 to 4 do

   begin

   nextx:=t[head,1]+dx[i];

   nexty:=t[head,2]+dy[i];

    if(nextx>0) and (nextx<=n) and (nexty>0) and (nexty<=m) andb[nextx,nexty]

      and (a[nextx,nexty]>=x) then

     begin

     inc(tail);

     t[tail,1]:=nextx;

     t[tail,2]:=nexty;

     b[nextx,nexty]:=false;

     if (nextx=ex) and (nexty=ey) then

     begin flag:=false; exit; end;

     end;

   end;

 untilhead=tail;

end;

 

procedure init;

 var i,j,l,head,tail,nextx,nexty,max,r:longint;

    ch:char;

begin

 readln(n,m); head:=0; tail:=0;

 fori:=1 to n do

  forj:=1 to m do

  a[i,j]:=-1;

 fori:=1 to n do

  begin

   forj:=1 to m do

    begin

     read(ch);

     ifch='V' then

     begin sx:=i; sy:=j; end;

     ifch='J' then

     begin ex:=i; ey:=j; end;

     ifch='+' then

     begin

      inc(tail);

      g[tail,1]:=i;

      g[tail,2]:=j;

      g[tail,3]:=0;

      a[i,j]:=0;

     end;

     end;

  readln;

  end;

 

max:=0;

 repeat

 inc(head);

  fori:=1 to 4 do

   begin

   nextx:=g[head,1]+dx[i];

   nexty:=g[head,2]+dy[i];

    if(nextx>0) and (nextx<=n) and (nexty>0) and (nexty<=m) and(a[nextx,nexty]=-1) then

     begin

     inc(tail);

     g[tail,1]:=nextx;

     g[tail,2]:=nexty;

     g[tail,3]:=g[head,3]+1;

     a[nextx,nexty]:=g[tail,3];

     if a[nextx,nexty]>max then max:=a[nextx,nexty];

     end;

   end;

 untilhead=tail;

l:=0; r:=max;

 whilel<=r do

  begin

  mid:=(l+r) shr 1;

  flag:=true;

  BFS;

   ifl=mid then break;

   ifflag then r:=mid-1

          else l:=mid;

  end;

 ifl=r then writeln(l)

     else

      begin

       flag:=true;

       mid:=r;

       bfs;

       if flag=false then writeln(r)

                      else writeln(l);

      end;

end;

 

begin

init;

end.

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: