BFS。军训晚上下雨无聊写的水题。
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 #include <queue> 6 #include <vector> 7 #define rep(i,l,r) for(int i = l; i <= r; i++) 8 #define clr(x,y) memset(x,y,sizeof(x)) 9 #define travel(x) for(Edge *p = last[x]; p; p = p -> pre) 10 using namespace std; 11 inline int read(){ 12 int ans = 0, f = 1; char c = getchar(); 13 for(; !isdigit(c); c = getchar()) if (c == '-') f = -1; 14 for(; isdigit(c); c = getchar()) ans = ans * 10 + c - '0'; 15 return ans * f; 16 } 17 int N, n, target; 18 struct Node{ 19 int num; vector <char> path; 20 }; 21 queue <Node> q; 22 inline int A(int x){ 23 int h = x / 10000; int l = x % 10000; 24 return l * 10000 + h; 25 } 26 inline int B(int x){ 27 int h = x / 10000; int l = x % 10000; 28 int hh = h / 10; int hl = h % 10; 29 int lh = l / 10; int ll = l % 10; 30 return hl * 10000000 + hh * 10000 + ll * 1000 + lh; 31 } 32 inline int C(int x){ 33 int t[9]; rep(i,1,8){ 34 t[8 - i + 1] = x % 10; 35 x = x / 10; 36 } 37 return t[1] * 1e7 + t[6] * 1e6 + t[2] * 1e5 + t[4] * 1e4 + t[5] * 1e3 + t[7] * 1e2 + t[3] * 10 + t[8]; 38 } 39 Node bfs(){ 40 while (!q.empty()) q.pop(); 41 Node s; s.num = 12348765; 42 q.push(s); 43 while (!q.empty()){ 44 Node now = q.front(); q.pop(); 45 if (now.path.size() > N) return now; 46 else{ 47 Node fun1 = now; 48 fun1.num = A(fun1.num); 49 fun1.path.push_back('A'); 50 if (fun1.num == target) return fun1; 51 else q.push(fun1); 52 Node fun2 = now; 53 fun2.num = B(fun2.num); 54 fun2.path.push_back('B'); 55 if (fun2.num == target) return fun2; 56 else q.push(fun2); 57 Node fun3 = now; 58 fun3.num = C(fun3.num); 59 fun3.path.push_back('C'); 60 if (fun3.num == target) return fun3; 61 else q.push(fun3); 62 } 63 } 64 } 65 void work(){ 66 target = 0; 67 rep(i,1,8){ 68 int x = read(); target = target * 10 + x; 69 } 70 Node out = bfs(); int cnt = out.path.size(); 71 if (cnt > N) printf("-1 "); 72 else{ 73 printf("%d ",cnt); 74 rep(i,0,cnt - 1) printf("%c",out.path[i]); 75 printf(" "); 76 } 77 } 78 int main(){ 79 N = read(); 80 while (N != -1){ 81 work(); N = read(); 82 } 83 return 0; 84 }