1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include <bits/stdc++.h> using namespace std; const int maxn = 1 << 24; int st, ed, mid, nxt[14][6], out[maxn]; bool av[maxn], bv[maxn];
vector<pair<int, int>> ap(maxn), bp(maxn);
int extend(queue<pair<int, int>> &aq, queue<pair<int, int>> &bq, bool av[], bool bv[], vector<pair<int, int>> &ap, int dir) { int sz = aq.size(); while (sz--) { int state = aq.front().first, step = aq.front().second; aq.pop(); int x, y, sx, sy, nsx, nsy, ns; for (int x = 0; x < 12; ++x) { if (dir == 1) { sx = (state >> (x << 1)) & 3, y = nxt[x][sx]; sy = (state >> (y << 1)) & 3; nsx = (sx + 1) & 3, nsy = (sy + 1) & 3; } else { sx = (state >> (x << 1)) & 3, y = nxt[x][(sx + 3) & 3]; sy = (state >> (y << 1)) & 3; nsx = (sx + 3) & 3, nsy = (sy + 3) & 3; } ns = state; ns -= (sx << (x << 1)), ns |= (nsx << (x << 1)); ns -= (sy << (y << 1)), ns |= (nsy << (y << 1)); if (av[ns]) continue; ap[ns] = {state, x + 1}; if (bv[ns]) { mid = ns; return 1 + step + bq.front().second; } av[ns] = 1; aq.push({ns, step + 1}); } } return -1; }
void bfs() { queue<pair<int, int>> aq, bq; aq.push({st, 0}), bq.push({0, 0}); av[st] = 1, bv[0] = 1; int res; while (!aq.empty() && !bq.empty()) { if (aq.size() <= bq.size()) { res = extend(aq, bq, av, bv, ap, 1); } else { res = extend(bq, aq, bv, av, bp, 2); } if (res != -1) break; } printf("%d\n", res); int idx = 0, tmp = mid; while (tmp != st) { out[++idx] = ap[tmp].second; tmp = ap[tmp].first; } while (idx) printf("%d ", out[idx--]); while (mid != 0) { out[++idx] = bp[mid].second; mid = bp[mid].first; } for (int i = 1; i <= idx; ++i) printf("%d ", out[i]); }
int main() { for (int button, i = 0; i < 12; ++i) { scanf("%d", &button); st |= (button - 1) << (i << 1); for (int j = 0; j < 4; ++j) { scanf("%d", &nxt[i][j]); nxt[i][j] -= 1; } } bfs(); return 0; }
|