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
| #include <bits/stdc++.h> using namespace std; int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
char opa[4] = {'u', 'r', 'd', 'l'}, opb[4] = {'d', 'l', 'u', 'r'}; string mid;
bool valid(int x, int y) { return x >= 0 && y >= 0 && x < 3 && y < 3; }
bool extend(queue<string> &aq, unordered_map<string, pair<string, char>> &ap, unordered_map<string, bool> &av, unordered_map<string, bool> &bv, char op[]) { int sz = aq.size(); while (sz--) { string s = aq.front(); aq.pop(); if (bv.count(s)) { mid = s; return true; } int x, y; for (int i = 0; i < s.length(); ++i) { if (s[i] == 'x') { x = i / 3, y = i % 3; break; } } string source = s; for (int i = 0; i < 4; ++i) { int nx = x + dx[i], ny = y + dy[i]; if (!valid(nx, ny)) continue; swap(s[x * 3 + y], s[nx * 3 + ny]); if (!av.count(s)) av[s] = 1, ap[s] = {source, op[i]}, aq.push(s); swap(s[x * 3 + y], s[nx * 3 + ny]); } } return false; }
string bfs(string S) { string T = "12345678x"; unordered_map<string, bool> av, bv; unordered_map<string, pair<string, char>> ap, bp; queue<string> aq, bq; aq.push(S), bq.push(T); av[S] = 1, bv[T] = 1; while (!aq.empty() && !bq.empty()) { bool flag = 0; flag = aq.size() < bq.size() ? extend(aq, ap, av, bv, opa) : extend(bq, bp, bv, av, opb); if (flag) break; } string res, tmp = mid; while (tmp != S) { res += ap[tmp].second; tmp = ap[tmp].first; } reverse(res.begin(), res.end()); while (mid != T) { res += bp[mid].second; mid = bp[mid].first; } return res; }
int main() { char c; string str, seq; while (cin >> c) { str += c; if (c != 'x') seq += c; } int num = 0; for (int i = 0; i < seq.length(); ++i) { for (int j = 0; j < i; ++j) { if (seq[i] < seq[j]) ++num; } } cout << ((num & 1) ? "unsolvable" : bfs(str)) << endl; return 0; }
|