POJ2286 The Rotation Game IDA*
基本上是裸的IDA*,细节有点难搞,需要耐心,,老久没一次A过题目了,,
也可以考虑使用bfs求解,但是状态较多无法有效判重,需要每次屏蔽掉两个数只处理一个数
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 //#define debug 5 using std :: min; 6 const int x1[8] = {0, 1, 3, 7, 12, 16, 21, 23}; 7 const int x2[8] = {0, 2, 4, 9, 13, 18, 22, 24}; 8 const int cent[9] = {0, 7, 8, 9, 12, 13, 16, 17, 18}; 9 const int makex[9] = {0, 1, 2, 3, 4, 2, 1, 4, 3}; 10 const int makep[9] = {0, 1, 1, 2, 2, 2, 2, 1, 1}; 11 int a[5][10]; 12 int num[30]; 13 int mov[30]; 14 int t[30]; 15 int maxd = 0; 16 17 int check(void) { 18 int cur = t[cent[1]]; 19 for (int i = 2; i <= 8; i++) if (cur != t[cent[i]]) return 0; 20 return cur; 21 } 22 void make(int x, int po) { // po == 1 up po == 2 down 23 if (po == 1) { 24 int cur = t[a[x][1]]; 25 for (int i = 2; i <= 7; i++) t[a[x][i-1]] = t[a[x][i]]; 26 t[a[x][7]] = cur; 27 } else { 28 int cur = t[a[x][7]]; 29 for (int i = 6; i >= 1; i--) t[a[x][i+1]] = t[a[x][i]]; 30 t[a[x][1]] = cur; 31 } 32 } 33 int h(int x) { 34 int tans = 0; 35 for (int i = 1; i <= 8; i++) if (t[cent[i]] != x) tans++; 36 return (tans); 37 } 38 bool dfs(int d) { 39 #ifdef debug 40 printf(" %d %d\n", t[1], t[2]); 41 printf(" %d %d\n", t[3], t[4]); 42 for (int i = 5; i <= 11; i++) printf("%d ", t[i]); 43 printf("\n"); 44 printf(" %d %d\n", t[12], t[13]); 45 for (int i = 14; i <= 20; i++) printf("%d ", t[i]); 46 printf("\n"); 47 printf(" %d %d\n", t[21], t[22]); 48 printf(" %d %d\n", t[23], t[24]); 49 printf("\n"); 50 #endif 51 if (d == maxd + 1) { 52 if (check() > 0) return 1; 53 return 0; 54 } 55 int needd = h(1); 56 needd = min(needd, h(2)); 57 needd = min(needd, h(3)); 58 if (d + needd - 1 > maxd) return 0; 59 for (int i = 1; i <= 8; i++) { 60 mov[d] = i; 61 make(makex[i], makep[i]); 62 if (dfs(d + 1)) return 1; 63 if (makep[i] == 1) make(makex[i], 2); 64 else make(makex[i], 1); 65 } 66 return 0; 67 68 } 69 int main () { 70 while (scanf("%d", &t[1]) == 1 && t[1]) { 71 for (int i = 2; i <= 24; i++) scanf("%d", &t[i]); 72 for (int i = 1; i <= 7; i++) a[1][i] = x1[i]; 73 for (int i = 1; i <= 7; i++) a[2][i] = x2[i]; 74 for (int i = 1; i <= 7; i++) a[3][i] = i + 4; 75 for (int i = 1; i <= 7; i++) a[4][i] = i + 13; 76 /* 77 for (int i = 1; i <= 7; i++) printf("%d ", a[1][i]); 78 printf("\n"); 79 for (int i = 1; i <= 7; i++) printf("%d ", a[2][i]); 80 printf("\n"); 81 for (int i = 1; i <= 7; i++) printf("%d ", a[3][i]); 82 printf("\n"); 83 for (int i = 1; i <= 7; i++) printf("%d ", a[4][i]); 84 printf("\n"); 85 */ 86 int cur = check(); 87 if (cur != 0) { 88 printf("No moves needed\n%d\n", cur); 89 continue; 90 } 91 for (maxd = 1; ; maxd++) { 92 if (dfs(1)) { 93 for (int i = 1; i <= maxd; i++) printf("%c", mov[i] - 1 + 'A'); 94 printf("\n"); 95 printf("%d\n", check()); 96 break; 97 } 98 } 99 } 100 return 0; 101 }