hdu1429 胜利大逃亡(续)

广搜+状态压缩

用一个三维的hash来标记当前位置和拥有的钥匙,由于钥匙一共10把,所以一共有2^10种组合,开到hash[21][21][1025]即可。

好像除了用位运算来记录钥匙串没什么好说的了……

1 #include <stdio.h>
2 #include <string.h>
3 typedef struct{
4 int x,y,t;
5 int key;
6 }QUEUE;
7 QUEUE q[500000];
8 const int dirc[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
9 int n,m,t;
10 bool hash[21][21][1025];
11 char map[21][21];
12
13 int bfs(int strX, int strY){
14 int top,tail,i,strT,strK,nextX,nextY,nextT,nextK;
15 top = tail = 0;
16 q[tail].x = strX;
17 q[tail].y = strY;
18 q[tail].t = 0;
19 q[tail++].key = 0;
20 hash[strX][strY][0] = true;
21 while(top < tail){
22 strX = q[top].x;
23 strY = q[top].y;
24 strT = q[top].t;
25 strK = q[top++].key;
26 if(map[strX][strY] == '^' && strT < t)
27 return strT;
28 else if(strT >= t)
29 return -1;
30 for(i = 0; i < 4; i++){
31 nextX = strX + dirc[i][0];
32 nextY = strY + dirc[i][1];
33 nextT = strT + 1;
34 nextK = strK;
35 if(nextX>=0&&nextY>=0&&nextX<n&&nextY<m&&map[nextX][nextY]!='*'){
36 if(map[nextX][nextY] >= 'A' && map[nextX][nextY] <= 'J'){
37 if(strK >> map[nextX][nextY] - 'A' & 1 && !hash[nextX][nextY][nextK]){
38 hash[nextX][nextY][nextK] = true;
39 q[tail].x = nextX;
40 q[tail].y = nextY;
41 q[tail].t = nextT;
42 q[tail++].key = nextK;
43 }
44 }
45 else if(map[nextX][nextY] >= 'a' && map[nextX][nextY] <= 'j'){
46 nextK = nextK | 1 << map[nextX][nextY] - 'a';
47 if(!hash[nextX][nextY][nextK]){
48 hash[nextX][nextY][nextK] = true;
49 q[tail].x = nextX;
50 q[tail].y = nextY;
51 q[tail].t = nextT;
52 q[tail++].key = nextK;
53 }
54 }
55 else{
56 if(!hash[nextX][nextY][nextK]){
57 hash[nextX][nextY][nextK] = true;
58 q[tail].x = nextX;
59 q[tail].y = nextY;
60 q[tail].t = nextT;
61 q[tail++].key = nextK;
62 }
63 }
64 }
65 }
66 }
67 return -1;
68 }
69 int main (void){
70 int i,j;
71 int strX,strY,endX,endY,ans;
72 // freopen("in.txt","r",stdin);
73 while(~scanf("%d%d%d",&n,&m,&t)){
74 getchar();
75 memset(hash,0,sizeof(hash));
76 for(i = 0; i < n; i++){
77 for(j = 0; j < m; j++){
78 map[i][j] = getchar();
79 if(map[i][j] == '@'){
80 strX = i;
81 strY = j;
82 }
83 }
84 getchar();
85 }
86 ans = bfs(strX,strY);
87 printf("%d\n",ans);
88 }
89 return 0;
90 }

原文地址:https://www.cnblogs.com/deadblue/p/2041230.html