洛谷p3956 棋盘(NOIP2017 t3)
在noip考场上本来以为只能骗暴力分,没想到最后A了;
本蒟蒻的做法比较简(zhi)单(zhang):记忆化深搜(考场上本来是想打广搜的,但我深搜稳一点就这样打了);
具体:每个点用一个f数组记录当前位置到这个点的最优值,如果大于等于就跳出,否则更新继续做;
深搜的过程中开个桶记录每个点是否无色,如果无色要注意下个走的点不能有色,如果下个点要走无色的格子,这里可以采取一个贪心的策略:把那个格子的颜色设置成当前这个格子的颜色;
要注意的是:走的过程中是可以向四个方向走的,并且要回溯(我一个dalao同学就忘了回溯才拿了40);
附蒟蒻丑陋的代码。。。
1 var n,m,i,j,k,l,x,y,z:longint; 2 a:array[0..101,0..101] of longint; 3 b:array[0..101,0..101] of boolean; 4 f:array[0..101,0..101] of longint; 5 procedure try(x,y,z,kk:longint); 6 begin 7 if (x>m)or(y>m)or(x<1)or(y<1) then exit; 8 if b[x,y] then exit; 9 if z>=f[x,y] then exit; 10 if (x=m)and(y=m) then 11 begin 12 if z<k then k:=z; 13 exit; 14 end; 15 f[x,y]:=z; 16 inc(l); 17 b[x,y]:=true; 18 if a[x,y]=1 then 19 begin 20 if a[x+1,y]=1 then try(x+1,y,z,1) else 21 if a[x+1,y]=2 then try(x+1,y,z+1,1) else 22 if kk=1 then 23 begin 24 a[x+1,y]:=1; 25 try(x+1,y,z+2,0); 26 a[x+1,y]:=0; 27 end; 28 if a[x,y+1]=1 then try(x,y+1,z,1) else 29 if a[x,y+1]=2 then try(x,y+1,z+1,1) else 30 if kk=1 then 31 begin 32 a[x,y+1]:=1; 33 try(x,y+1,z+2,0); 34 a[x,y+1]:=0; 35 end; 36 if a[x-1,y]=1 then try(x-1,y,z,1) else 37 if a[x-1,y]=2 then try(x-1,y,z+1,1) else 38 if kk=1 then 39 begin 40 a[x-1,y]:=1; 41 try(x-1,y,z+2,0); 42 a[x-1,y]:=0; 43 end; 44 if a[x,y-1]=1 then try(x,y-1,z,1) else 45 if a[x,y-1]=2 then try(x,y-1,z+1,1) else 46 if kk=1 then 47 begin 48 a[x,y-1]:=1; 49 try(x,y-1,z+2,0); 50 a[x,y-1]:=0; 51 end; 52 end else 53 if a[x,y]=2 then 54 begin 55 if a[x+1,y]=1 then try(x+1,y,z+1,1) else 56 if a[x+1,y]=2 then try(x+1,y,z,1) else 57 if kk=1 then 58 begin 59 a[x+1,y]:=2; 60 try(x+1,y,z+2,0); 61 a[x+1,y]:=0; 62 end; 63 if a[x,y+1]=1 then try(x,y+1,z+1,1) else 64 if a[x,y+1]=2 then try(x,y+1,z,1) else 65 if kk=1 then 66 begin 67 a[x,y+1]:=2; 68 try(x,y+1,z+2,0); 69 a[x,y+1]:=0; 70 end; 71 if a[x-1,y]=1 then try(x-1,y,z+1,1) else 72 if a[x-1,y]=2 then try(x-1,y,z,1) else 73 if kk=1 then 74 begin 75 a[x-1,y]:=2; 76 try(x-1,y,z+2,0); 77 a[x-1,y]:=0; 78 end; 79 if a[x,y-1]=1 then try(x,y-1,z+1,1) else 80 if a[x,y-1]=2 then try(x,y-1,z,1) else 81 if kk=1 then 82 begin 83 a[x,y-1]:=2; 84 try(x,y-1,z+2,0); 85 a[x,y-1]:=0; 86 end; 87 end; 88 b[x,y]:=false; 89 end; 90 begin 91 assign(input,'chess.in'); 92 assign(output,'chess.out'); 93 reset(input); 94 rewrite(output); 95 k:=maxlongint div 3; 96 read(m,n); 97 for i:=1 to m do 98 for j:=1 to m do f[i,j]:=maxlongint; 99 for i:=1 to n do 100 begin 101 read(x,y,z); 102 a[x,y]:=z+1; 103 end; 104 try(1,1,0,1); 105 if k=maxlongint div 3 then write(-1) else 106 write(k); 107 close(input); 108 close(output); 109 end.