利用二进制来表示房间灯的情况,再用独立参数表示现在所在房间,bfs完成查找,递归完成输出
注意一下每组数据后要换行,不要忘了
/* author:jxy lang:C/C++ university:China,Xidian University **If you need to reprint,please indicate the source** */ #include <cstdio> #include <cstring> #include <queue> using namespace std; int vis[11][2000]; int pre[11][2000]; int r,d,s; struct node { int step,now,state; }; queue<node> q; vector<int> sw[11]; vector<int> door[11]; node now,next; bool input() { scanf("%d%d%d",&r,&d,&s); if(r+d+s==0)return 0; int i,f,t; for(i=1;i<=r;i++) { sw[i].clear(); door[i].clear(); } for(i=0;i<d;i++) { scanf("%d%d",&f,&t); door[f].push_back(t); door[t].push_back(f); } for(i=0;i<s;i++) { scanf("%d%d",&f,&t); sw[f].push_back(t); } while(!q.empty())q.pop(); memset(vis,0,sizeof(vis)); i=1<<(r-1);//初始状态100000 vis[1][i]=1;pre[1][i]=0; now.state=i;now.now=1;now.step=1; q.push(now); return 1; } void output(int Now,int state)//递归输出 { int ln,ls,nn=pre[Now][state]; if(nn==0)return; ln=nn%100; ls=nn/100; output(ln,ls); if(ln!=Now)printf("- Move to room %d.\n",Now); else { int t=ls^state,i,flag; for(i=0;i<r&&!(t&1);i++,t>>=1); flag=ls&(1<<i); printf("- Switch %s light in room %d.\n",flag?"off":"on",r-i); } } void solve() { int i,len,k,t,Now,nn; while(!q.empty()&&!vis[r][1])//末状态0000001 { now=q.front();q.pop(); Now=now.now; nn=now.state*100+Now; next.step=now.step+1; len=sw[Now].size(); for(i=0;i<len;i++)//开关灯 { k=sw[Now][i]; if(k==Now)continue;//不能开关自己的灯 t=now.state^(1<<(r-k));//异或改变这一位的值 if(vis[Now][t])continue; vis[Now][t]=next.step; pre[Now][t]=nn; next.state=t; next.now=Now; q.push(next); } len=door[Now].size(); for(i=0;i<len;i++)//走到有灯的房间 { k=door[Now][i]; if(((1<<(r-k))&now.state)==0||vis[k][now.state])continue; vis[k][now.state]=next.step; pre[k][now.state]=nn; next.state=now.state; next.now=k; q.push(next); } } if(vis[r][1]) { printf("The problem can be solved in %d steps:\n",vis[r][1]-1); output(r,1); } else printf("The problem cannot be solved.\n"); } int main() { int T=0; while(input()) { printf("Villa #%d\n",++T); solve(); puts(""); } }