最近想刷一些搜索题目, 看到了这题, 这题就是个bfs需要点状压的小技巧, 感觉做搜索题目, 主要还是要仔细和耐心吧。。。
(此题在poj上有个trick, 就是一个房间开关灯时要按字典序, 读入后排个序就可以了。。。)
代码很丑:
#include <vector>
#include <queue>
#include <cstring>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
struct node {
int u;
int state;
node(int a = 0, int b = 0) {
u = a, state = b;
}
int hash() {
return u * 1024 + state;
}
};
struct fa {
int p;
int op;
int which;
};
const int n = 11005;
int lev[n];
fa fa[n];
vector<int> adj[15];
vector<int> ctrl[15];
queue<node> q;
void init(int n) {
for (int i = 0; i < n; i++) {
adj[i].clear();
ctrl[i].clear();
}
memset(lev, -1, sizeof(lev));
while (!q.empty()) q.pop();
}
void print(int id) {
if (fa[id].p == -1) return;
print(fa[id].p);
if (fa[id].op == 0)
printf("- Switch off light in room %d.\n", fa[id].which + 1);
else if (fa[id].op == 1)
printf("- Switch on light in room %d.\n", fa[id].which + 1);
else
printf("- Move to room %d.\n", fa[id].which + 1);
}
void bfs(int n) {
int u = 0, state = 1;
node st(u, state);
q.push(st);
int h = st.hash();
lev[h] = 0;
fa[h].p = -1;
u = n - 1, state = 1 << (n - 1);
node ed(u, state);
bool ok = 0;
while (!q.empty()) {
node cur = q.front();
q.pop();
if (cur.hash() == ed.hash()) {
ok = 1;
break;
}
int u = cur.u, h = cur.hash(), s = cur.state;
for (int i = 0; i < adj[u].size(); i++) {
int v = adj[u][i];
if (!(s & (1 << v))) continue;
node tar(v, s);
if (lev[tar.hash()] == -1) {
q.push(tar);
int tmp = tar.hash();
lev[tmp] = lev[h] + 1;
fa[tmp].p = h;
fa[tmp].op = 2;
fa[tmp].which = v;
}
}
for (int i = 0; i < ctrl[u].size(); i++) {
int t = ctrl[u][i];
if (t == u) continue;
int state = s ^ (1 << t);
node tar(u, state);
if (lev[tar.hash()] == -1) {
q.push(tar);
int tmp = tar.hash();
lev[tmp] = lev[h] + 1;
fa[tmp].p = h;
if (state & (1 << t))
fa[tmp].op = 1;
else
fa[tmp].op = 0;
fa[tmp].which = t;
}
}
}
if (ok) {
printf("The problem can be solved in %d steps:\n", lev[ed.hash()]);
print(ed.hash());
}
else {
puts("The problem cannot be solved.");
}
}
int main() {
int r, d, s, cas = 1, u, v;
while (scanf("%d%d%d", &r, &d, &s), r + d + s) {
printf("Villa #%d\n", cas++);
init(r);
for (int i = 0; i < d; i++) {
scanf("%d%d", &u, &v);
u--, v--;
adj[u].push_back(v);
adj[v].push_back(u);
}
for (int i = 0; i < s; i++) {
scanf("%d%d", &u, &v);
u--, v--;
ctrl[u].push_back(v);
}
for (int i = 0; i < r; i++)
sort(ctrl[i].begin(), ctrl[i].end());
bfs(r);
puts("");
}
return 0;
}