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 88 89 90 91
| #include <iostream> #include <cstring> #include <cmath> #include <queue> using namespace std; int powerOf10(int power) { if(power == 0) return 1; int res = 1, tmp = powerOf10(power >> 1); if(power & 1) return tmp * tmp * 10; return tmp * tmp; } inline int digit(int x) { int res = 0; while(x > 0) { x /= 10; res++; } return res; } inline int get(int base, int pos) { int db = digit(base); if(pos < 0 || pos >= db) return 1; return base / powerOf10(digit(base) - pos - 1) % 10; } inline int swap(int base, int x, int y) { int px = powerOf10(digit(base) - x - 1), py = powerOf10(digit(base) - y - 1); int nx = get(base, x), ny = get(base, y); base -= nx * px; base -= ny * py; base += nx * py; base += ny * px; return base; } inline int insert(int base, int pos, int x) { int pivot = powerOf10(digit(base) - pos), pre = base / pivot, post = base % pivot; int pdpost = powerOf10(digit(post)); return pre * pdpost * 10 + x * pdpost + post; } inline int erase(int base, int pos) { int pivot = powerOf10(digit(base) - pos - 1), pre = base / pivot, post = base % pivot; pre /= 10; return pre * powerOf10(digit(post)) + post; } int mem[1000010], start, n, dstart; queue<int> q; inline void update(int cur, int nxt) { if(mem[nxt] == -1) { mem[nxt] = mem[cur] + 1; q.push(nxt); } } void bfs() { q.push(start); memset(mem, -1, sizeof(mem)); mem[start] = 0; while(q.size()) { int cur = q.front(); q.pop(); int d = digit(cur); if(d == 1) continue; for(int i = 0; i < d; i++) { for(int j = i + 1; j < d; j++) { int nxt = swap(cur, i, j); update(cur, nxt); } } for(int i = 0; i < d; i++) { int nxt = erase(cur, i); update(cur, nxt); } if(d < dstart) for(int i = 1; i < d; i++) { for(int j = get(cur, i - 1) + 1; j < get(cur, i); j++) { int nxt = insert(cur, i, j); update(cur, nxt); } } } } int main() { cin >> start >> n; dstart = digit(start); bfs(); while(n--) { int target; cin >> target; cout << mem[target] << endl; } system("pause"); return 0; }
|