这个题的难点就是哈希判重,思路倒不是很抽象
我还是没有用哈希判重,也许是空间耗费太大吧,我觉得用二进制更好,更省空间,
对于灯的开闭用0,1表示2^10 = 1024是上限,但是若前面再加上房间状态的话就麻烦了,例如此时处在room号房间,怎样把room加进去而不耗费太多空间的话就容我思考一阵子了
若是room*binary的话,会出现重复,例如房间1,灯开闭状态为0 1 1,与房间3,灯的开闭为0 0 1 ,就出现了重复
若是room+1024+binary的话还是会出现重复,例如房1,灯011,与房3,灯001也出现重复
但,若是把room和binary看作一个X进制的两位数,当X>1024时,就不会重复,而且范围为0+0~~~10*1024+1024,所以这样以来即省了空间,又省了代码。我们还可以看出这样不会浪费空间的。
我写的代码先贴上了。。
代码如下:
#include <cstdio> #include <cstring> #define MN 100003 int ok, r, d, s, ans, door[11][11], swith[11][11]; int vis[MN], st[MN][11], pa[MN], fa[MN]; //用pa[]来记录路径, int is_ok(int cur) { if(!st[cur][r]) return 0; for(int i = 1; i < r; i++) if(st[cur][i]) return 0; return 1; } int try_to_insert(int cur) { int s = 0; for(int i = 1; i <= r; i++) s = s * 2 + st[cur][i]; s = s + 1024 * st[cur][0]; if(!vis[s]) { vis[s] = 1; return 1; } else return 0; } void bfs() { int rear = 0, front = 1; for(int i = 1; i <= r; i++) st[0][i] = 0; st[0][0] = st[0][1] = 1; try_to_insert(0); while(rear<front) { int t, now_room = st[rear][0]; if(now_room==r&&is_ok(rear)) { ok = 1; ans = rear; break; } for(int i = 1; i <= r; i++) if(swith[now_room][i]) { st[front][0] = now_room; if(now_room==i) continue; for(int j = 1; j <= r; j++) st[front][j] = st[rear][j]; st[front][i] = !st[rear][i]; if(st[rear][i]) t = -1; else t = 1; //若是开灯的话就记作正的i,若是闭灯就记作-1*i if(try_to_insert(front)) { pa[front] = t*i; fa[front] = rear; front++; } } for(int i = 1; i <= r; i++) if(door[now_room][i]&&st[rear][i]) { st[front][0] = i; for(int j = 1; j <= r; j++) st[front][j] = st[rear][j]; if(try_to_insert(front)) { pa[front] = i+10; fa[front] = rear; front++; } //若是挪动房间的话,就记作i+10. } rear++; } } void print_path(int cur,int n) { if(!cur) { printf("The problem can be solved in %d steps:\n",n); return;} print_path(fa[cur],n+1); if(pa[cur]>10) printf("- Move to room %d.\n",pa[cur]-10); else if(pa[cur]>0) printf("- Switch on light in room %d.\n",pa[cur]); else printf("- Switch off light in room %d.\n",pa[cur]*-1); } int main () { int cas = 0, a, b; while(scanf("%d%d%d",&r,&d,&s), r+d+s) { memset(vis,0,sizeof(vis)); memset(door,0,sizeof(door)); memset(swith,0,sizeof(swith)); for(int i = 0; i < d; i++) { scanf("%d%d",&a,&b); door[a][b] = door[b][a] = 1; } for(int i = 0; i < s; i++) { scanf("%d%d",&a,&b); swith[a][b] = 1; } ans = 0; ok = 0; bfs(); printf("Villa #%d\n",++cas); if(ok) print_path(ans,0); else printf("The problem cannot be solved.\n"); puts(""); } return 0; }