状态总数10*2^10=10240,hash判重即可
注意点:在A房间不能关掉自己房间的灯(oh,my god,太伤了!)
#include<stdio.h> #include<string.h> #include<queue> using namespace std; int r,d,s,sum; bool map[11][11],sw[11][11]; bool visit[11][1100]; int type[11][1100]; // move 1 on 2 off 3 int before[11][1100]; int beforestate[11][1100]; struct point{ int room; int state; int step; }; void bfs(){ int i; queue<struct point>que; struct point sta; sta.room=1; sta.state=1; sta.step=0; visit[1][1]=1; que.push(sta); while(!que.empty()){ struct point tem=que.front(); que.pop(); for(i=1;i<=r;i++){ if(i==tem.room || !map[tem.room][i]) continue; if(!(tem.state&(1<<(i-1)))) continue; if(visit[i][tem.state]) continue; struct point tmp; visit[i][tem.state]=1; type[i][tem.state]=1; before[i][tem.state]=tem.room; beforestate[i][tem.state]=tem.state; tmp.room=i; tmp.state=tem.state; tmp.step=tem.step+1; if(tmp.room==r && tmp.state==(1<<(r-1))){ sum=tmp.step; return ; } que.push(tmp); } for(i=1;i<=r;i++){ if(i==tem.room || !sw[tem.room][i]) continue; int cur=tem.state^(1<<(i-1)); if(visit[tem.room][cur]) continue; visit[tem.room][cur]=1; if((tem.state&(1<<(i-1)))) type[tem.room][cur]=3; else type[tem.room][cur]=2; before[tem.room][cur]=i; beforestate[tem.room][cur]=tem.state; struct point tmp; tmp.room=tem.room; tmp.state=cur; tmp.step=tem.step+1; if(tmp.room==r && tmp.state==(1<<(r-1))){ sum=tmp.step; return ; } que.push(tmp); } } } void print_path(int state,int room){ if(room==1 && state==1) return; if(type[room][state]==1){ print_path(state,before[room][state]); printf(“- Move to room %d.\n”,room); } else if(type[room][state]==2){ print_path(beforestate[room][state],room); printf(“- Switch on light in room %d.\n”,before[room][state]); } else if(type[room][state]==3){ print_path(beforestate[room][state],room); printf(“- Switch off light in room %d.\n”,before[room][state]); } } int main(){ int i,u,v,ca=0; while(scanf(“%d %d %d”,&r,&d,&s) && !(r==0 && d==0 && s==0)){ printf(“Villa #%d\n”,++ca); sum=0; memset(map,0,sizeof(map)); memset(sw,0,sizeof(sw)); memset(visit,0,sizeof(visit)); for(i=1;i<=d;i++){ scanf(“%d %d”,&u,&v); map[u][v]=map[v][u]=1; } for(i=1;i<=s;i++){ scanf(“%d %d”,&u,&v); sw[u][v]=1; } bfs(); if(!visit[r][1<<(r-1)]){ printf(“The problem cannot be solved.\n”); } else{ printf(“The problem can be solved in %d steps:\n”,sum); print_path(1<<(r-1),r); } printf(“\n”); } return 0; }