Problem UVA1434-The Rotation Game
Accept:2209 Submit:203
Time Limit: 3000 mSec
Problem Description
Input
The input consists of no more than 30 test cases. Each test case has only one line that contains 24 numbers, which are the symbols of the blocks in the initial configuration. The rows of blocks are listed from top to bottom. For each row the blocks are listed from left to right. The numbers are separated by spaces. For example, the first test case in the sample input corresponds to the initial configuration in Fig.1. There are no blank lines between cases. There is a line containing a single ‘0’ after the last test case that ends the input.
Output
For each test case, you must output two lines. The first line contains all the moves needed to reach the final configuration. Each move is a letter, ranging from ‘A’ to ‘H’, and there should not be any spaces between the letters in the line. If no moves are needed, output ‘No moves needed’ instead. In the second line, you must output the symbol of the blocks in the center square after these moves. If there are several possible solutions, you must output the one that uses the least number of moves. If there is still more than one possible solution, you must output the solution that is smallest in dictionary order for the letters of the moves. There is no need to output blank lines between cases.
Sample Input
1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3
0
Sample Ouput
AC
2
DDHH
2
题解:做了两道IDA*的题,对这个算法有了一个初步的印象,感觉挺强大的,而且代码短,思路清晰。
这个题搜索的框架很简单(IDA*的好处),但是具体实现起来不太容易。第一个技巧,用静态数组来搞定旋转的问题,第二个技巧,使用rev数组来精简代码。
rev数组不只是节省了一些代码量,而且可以轻松实现回溯时数组的复原,否则还要先把原数组存到一个另一个数组里,回溯时再copy回来,省了空间和时间,非常巧妙。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <algorithm> 6 7 using namespace std; 8 9 /* 10 00 01 11 02 03 12 04 05 06 07 08 09 10 13 11 12 14 13 14 15 16 17 18 19 15 20 21 16 22 23 17 */ 18 19 const int maxn = 24; 20 int num[maxn]; 21 char ans[10000]; 22 int maxd; 23 24 int line[8][7] = 25 { 26 { 0, 2, 6,11,15,20,22}, 27 { 1, 3, 8,12,17,21,23}, 28 {10, 9, 8, 7, 6, 5, 4}, 29 {19,18,17,16,15,14,13}, 30 }; 31 32 const int rev[8] = { 5,4,7,6,1,0,3,2 }; 33 const int center[8] = { 6,7,8,11,12,15,16,17 }; 34 35 bool is_ok() { 36 int t = num[center[0]]; 37 for (int i = 1; i < 8; i++) { 38 if (num[center[i]] != t) return false; 39 } 40 return true; 41 } 42 43 int cal(int tar) { 44 int cnt = 0; 45 for (int i = 0; i < 8; i++) { 46 if (num[center[i]] != tar) cnt++; 47 } 48 return cnt; 49 } 50 51 inline int h() { 52 return min(min(cal(1), cal(2)), cal(3)); 53 } 54 55 void move(int i) { 56 int tmp = num[line[i][0]]; 57 for (int j = 0; j < 6; j++) { 58 num[line[i][j]] = num[line[i][j + 1]]; 59 } 60 num[line[i][6]] = tmp; 61 } 62 63 bool dfs(int d) { 64 if (is_ok()) { 65 ans[d] = '