#include #include #include using namespace std; struct status{ int lightBits, room, step; struct status *next; }status[1024][10]; struct door{ int r1, r2; int other(int r) { return r == r1 ? r2 : r == r2 ? r1 : -1; } } door[100]; struct control { int plc, ctld; } control[100]; int mark[1024][10]; int numDoor, numControl, numRoom; int ENCODE[10]; int Decode(int x) { for (int i=0; i < numRoom; i++) if (ENCODE[i] == x) return i; return -1; } void Input() { int r1, r2; for (int i=0; i >r1>>r2; struct door d = {r1-1, r2-1}; door[i] = d; } for (int i=0; i >r1>>r2; //Discards controls and lights in same room. if (r1 == r2) { i--; numControl--; continue; } struct control c = {r1-1, r2-1}; control[i] = c; } } bool Solve() { memset(mark, 0, sizeof(mark)); struct status *final = &status[ENCODE[numRoom-1]][numRoom-1]; final->next = NULL; final->step = 0; queue Q; mark[ENCODE[numRoom-1]][numRoom-1] = 1; Q.push(final); bool done = false; /** * BFS search. **/ struct status *cur; while (!Q.empty()) { cur = Q.front(); Q.pop(); int lightBits = cur->lightBits, room = cur->room, step = cur->step; if (lightBits == ENCODE[0] && room == 0) { done = true; break; } for (int i = 0; i 0 ) && (!mark[lightBits][oth]) ) { mark[lightBits][oth]=1; struct status *stat=&status[lightBits][oth]; stat->next = cur; stat->step = step+1; Q.push(stat); } } for (int i=0; i next = cur; stat->step = step+1; Q.push(stat); } } } if (!done) return false; cout<<"The problem can be solved in "< step<<" steps:"< next) { int bits1 = cur->lightBits, bits2 = cur->next->lightBits, room1 = cur->room, room2 = cur->next->room; if (bits1 == bits2) cout<<"- Move to room "< <<"."< next; } return true; } int main(int argc, char *argv[]) { ENCODE[0] = 1; for (int i=1; i<10; i++) { ENCODE[i] = ENCODE[i-1] << 1; } for (int i=0; i<1024; i++) for (int j=0; j<10; j++) { struct status temp = {i, j, 0, NULL}; status[i][j] = temp; } int t=1; while (1) { cin>>numRoom>>numDoor>>numControl; if (numRoom == 0) break; Input();
cout<<"Villa #"<<t++<<endl;
if (!Solve()) cout<<"The problem cannot be solved."<<endl;
cout<<endl; }}