标签:pos from others ack make algo iostream cat sha
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 35625 Accepted Submission(s): 9219
Special Judge
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 x
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8 5 6 7 8 5 6 7 8
9 x 10 12 9 10 x 12 9 10 11 12 9 10 11 12
13 14 11 15 13 14 11 15 13 14 x 15 13 14 15 x
r-> d-> r->
1 #include <iostream> 2 #include <queue> 3 #include <cstring> 4 #include <cstdio> 5 #include <string> 6 #include <algorithm> 7 #include <set> 8 #include <map> 9 10 using namespace std; 11 12 map<string, char> mp; // 存储当前局面和方向 13 map<string, string>pre; // 存储当前局面和上一局面 14 15 int flag = 0; 16 17 struct node 18 { 19 int cur; // x在string中的下标 20 string s; // 当前局面 21 }nod; 22 23 string Swap(string s, int x, int y) 24 { 25 swap(s[x], s[y]); 26 return s; 27 } 28 29 void Print(string str) // 递归打印结果 30 { 31 if(mp[str] == ‘#‘) 32 return; 33 Print(pre[str]); 34 cout << mp[str]; 35 } 36 37 void bfs() 38 { 39 queue<node> Q; 40 41 Q.push(nod); 42 mp[nod.s] = ‘#‘; 43 44 node p,t; 45 while(!Q.empty()) 46 { 47 p = Q.front(); 48 Q.pop(); 49 50 if(p.s == "12345678x") 51 { 52 flag = 1; 53 Print("12345678x"); 54 } 55 56 for(int i = 0; i < 4; ++i) 57 { 58 if(i == 3) // 向左 59 { 60 if(p.cur % 3 != 0) // 下标为0,3,6的不能向左移动 61 { 62 t.s = Swap(p.s, p.cur, p.cur-1); 63 if(mp.count(t.s) == 0) 64 { 65 mp[t.s] = ‘l‘; 66 pre[t.s] = p.s; 67 t.cur = p.cur - 1; 68 Q.push(t); 69 } 70 71 } 72 } 73 else if(i == 2) // 向右 74 { 75 if(p.cur % 3 != 2) // 下标为2,5,8的不能向右移动 76 { 77 t.s = Swap(p.s, p.cur, p.cur+1); 78 if(mp.count(t.s) == 0) 79 { 80 mp[t.s] = ‘r‘; 81 pre[t.s] = p.s; 82 t.cur = p.cur + 1; 83 Q.push(t); 84 } 85 86 } 87 } 88 else if(i == 1) // 向上 89 { 90 if(p.cur > 2) // 下标为0,1,2的不能向上移动 91 { 92 t.s = Swap(p.s, p.cur, p.cur-3); 93 if(mp.count(t.s) == 0) 94 { 95 mp[t.s] = ‘u‘; 96 pre[t.s] = p.s; 97 t.cur = p.cur - 3; 98 Q.push(t); 99 } 100 101 } 102 } 103 else if(i == 0) // 向下 104 { 105 if(p.cur < 6) // 下标为6,7,8的不能向下移动 106 { 107 t.s = Swap(p.s, p.cur, p.cur+3); 108 if(mp.count(t.s) == 0) 109 { 110 mp[t.s] = ‘d‘; 111 pre[t.s] = p.s; 112 t.cur = p.cur + 3; 113 Q.push(t); 114 } 115 } 116 } 117 118 } 119 } 120 } 121 122 123 int main() 124 { 125 126 char c; 127 string str; 128 int k; 129 for(int i = 0; i < 9; ++i) 130 { 131 cin >> c; 132 str += c; 133 if(c == ‘x‘) 134 k = i; // 记录x的初始下标 135 } 136 137 nod.s = str; 138 nod.cur = k; 139 140 bfs(); 141 if(flag == 0) 142 cout << "unsolvable"; 143 cout << endl; 144 145 return 0; 146 }
标签:pos from others ack make algo iostream cat sha
原文地址:https://www.cnblogs.com/FengZeng666/p/11302477.html