UVA 10422 - Knights in FEN
链结戳我.
这是一道用BFS+Hash Table的题目。我在forum里面试了所有的test cases,都通过了,但是就是不知道为什么不能AC。眼泪掉下来T.T。
View Code
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 5 typedef int State[25]; 6 const int MAXSTATE = 1000000; 7 const int MAXHASHSIZE = 10000000; 8 9 State st[MAXSTATE], 10 goal = { 11 1,1,1,1,1, 12 0,1,1,1,1, 13 0,0,2,1,1, 14 0,0,0,0,1, 15 0,0,0,0,0 16 }; 17 18 int dist[MAXSTATE]; 19 int head[MAXHASHSIZE], next[MAXSTATE]; 20 21 const int dx[] = {-2, -2, 2, 2, -1, -1, 1, 1}; 22 const int dy[] = {-1, 1, -1, 1, -2, 2, -2, 2}; 23 24 void init_lookup_table(){ 25 memset(head, 0, sizeof(head)); 26 memset(next, 0, sizeof(next)); 27 } 28 29 int hash(State& s) { 30 int v = 0; 31 for (int i = 0; i < 25; i++){ 32 v += (s[i]<<i); 33 } 34 return v % MAXHASHSIZE; 35 } 36 37 bool try_to_insert(int s) { 38 int h = hash(st[s]); 39 // cout << h << endl; 40 int u = head[h]; 41 while (u){ 42 if (memcmp(st[u], st[s], sizeof(st[s])) == 0) 43 return false; 44 u = next[u]; 45 } 46 next[s] = head[h]; 47 head[h] = s; 48 return true; 49 } 50 51 int bfs() { 52 init_lookup_table(); 53 int front = 1, rear = 2; 54 try_to_insert(1); 55 while (front < rear){ 56 State& s = st[front]; 57 if (dist[front] > 10) 58 return -1; 59 60 if (memcmp(s, goal, sizeof(s)) == 0) 61 return front; 62 63 int z; 64 for (z = 0; z < 25; z++) 65 if (s[z] == 2) 66 break; 67 int x = z/5, y = z%5; 68 for (int i = 0; i < 8; i++){ 69 State& t = st[rear]; 70 int newx = x + dx[i], 71 newy = y + dy[i]; 72 int newz = newx*5 + newy; 73 if (newx >= 0 && newx < 5 && newy >= 0 && newy < 5){ 74 memcpy(&t, &s, sizeof(s)); 75 t[newz] = s[z]; 76 t[z] = s[newz]; 77 dist[rear] = dist[front]+1; 78 if (try_to_insert(rear)){ 79 rear++; 80 } 81 } 82 } 83 front++; 84 } 85 } 86 87 88 89 int main(int argc, char *argv[]){ 90 int cases; 91 const int MAXLENGTH = 10; 92 char ch[MAXLENGTH]; 93 cin.getline(ch, MAXLENGTH); 94 cases = ch[0] - '0'; 95 96 while (cases--){ 97 memset(st, 0, sizeof(st)); 98 memset(dist, 0, sizeof(dist)); 99 for (int i = 0; i < 5; i++){ 100 cin.getline(ch, MAXLENGTH); 101 for (int j = 0; j < 5; j++){ 102 if (ch[j] == ' ') 103 st[1][i*5+j] = 2; 104 else 105 st[1][i*5+j] = ch[j] - '0'; 106 } 107 } 108 109 // cout << endl; 110 // for (int i = 0; i < 5; i++){ 111 // for (int j = 0; j < 5; j++) 112 // cout << st[1][i*5+j]; 113 // cout << endl; 114 // } 115 116 int ans = bfs(); 117 if (ans != -1){ 118 cout << "Solvable in " << dist[ans] << " move(s)." << endl; 119 } 120 else 121 cout << "Unsolvable in less than 11 move(s)." << endl; 122 } 123 return 0; 124 }
这里的东西都是自娱自乐的.我只是抱着构思算法的心态去做UVA的题.
我所有的code都不可能AC的.因为我就没想着让它能AC.