bfs+visit[]+康托展开
1 #include <iostream> 2 #include <queue> 3 #include <cstring> 4 5 using namespace std; 6 7 int b[9]; 8 int temp[9]; 9 int fac[]={1,1,2,6,24,120,720,5040, 40320}; 10 bool visit[500005]; 11 12 struct node { 13 int c; 14 string s; 15 int m; 16 int number; 17 node() 18 { 19 s = ""; 20 c = 1; 21 m=0; 22 number=12348765; 23 } 24 }; 25 26 int cantor(int n) 27 { 28 for(int i = 7; i >= 0; i--) 29 { 30 b[i] = n % 10; 31 n /= 10; 32 } 33 34 int res=0; 35 for(int i=0; i<8; i++) 36 { 37 int temp=0; 38 for(int j=i+1; j<8; j++) 39 { 40 if(b[j] < b[i]) 41 temp++; 42 } 43 res += fac[8-i-1]*temp; 44 } 45 return res+1; 46 } 47 48 node ca(node a) 49 { 50 int tmp = a.number/1000%10*1e7 + a.number/100%10*1e6 + a.number/10%10*1e5 + a.number%10*1e4 + 51 a.number/(10000000)%10*1e3 + a.number/1000000%10*1e2 + a.number/100000%10*10 + a.number/10000%10; 52 a.s += 'A'; 53 a.m++; 54 a.number = tmp; 55 //a.c = cantor(a.number); 56 return a; 57 } 58 59 node cb(node a) 60 { 61 int tmp = a.number/10000%10*1e7 + a.number/10000000%10*1e6 + a.number/1000000%10*1e5 + 62 a.number/100000%10*1e4 + a.number%10*1e3 + a.number/1000%10*1e2 + a.number/100%10*10 + a.number/10%10; 63 a.m++; 64 a.number = tmp; 65 a.s += 'B'; 66 //a.c = cantor(a.number); 67 return a; 68 } 69 70 node cc(node a) 71 { 72 int tmp = a.number/10000000%10*1e7 + a.number/100%10*1e6 + a.number/1000000%10*1e5 + a.number/10000%10*1e4 73 + a.number/1000%10*1e3 + a.number/10%10*1e2 + a.number/100000%10*10 + a.number%10; 74 a.number = tmp; 75 a.m++; 76 a.s += 'C'; 77 //a.c = cantor(a.number); 78 return a; 79 } 80 81 int main() 82 { 83 int n; 84 85 while(cin >> n) 86 { 87 if(n == -1) 88 break; 89 90 memset(visit, 0, sizeof(visit)); 91 92 node a; 93 node t; 94 for(int i=0; i<8; i++) 95 cin >> temp[i]; 96 t.number = temp[0]*1e7+temp[1]*1e6+temp[2]*1e5+temp[3]*1e4+temp[4]*1e3+temp[5]*1e2+temp[6]*1e1+temp[7]; 97 t.c = cantor(t.number); 98 99 node res; 100 queue<node>q; 101 q.push(a); 102 bool flag=1; 103 while(!q.empty()){ 104 res = q.front(); 105 q.pop(); 106 if(res.m > n) 107 { 108 flag=0; 109 break; 110 } 111 if(res.number == t.number) 112 break; 113 if(!visit[cantor(ca(res).number)]) 114 { 115 visit[cantor(ca(res).number)] = 1; 116 q.push(ca(res)); 117 } 118 if(!visit[cantor(cb(res).number)]) 119 { 120 visit[cantor(cb(res).number)] = 1; 121 q.push(cb(res)); 122 } 123 if(!visit[cantor(cc(res).number)]) 124 { 125 visit[cantor(cc(res).number)] = 1; 126 q.push(cc(res)); 127 } 128 129 130 } 131 if(flag) 132 cout << res.m << " " << res.s << endl; 133 else 134 cout << -1 << endl; 135 } 136 return 0; 137 }