[SOL] #148. 数字格子问题

说实话这题确实挺菜的。。。

废话少说,直接上代码^O^ 

Code:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 inline int read() {
 4     int x = 0 , f = 1; char ch = getchar();
 5     for ( ; !isdigit(ch) ; ch = getchar()) if (ch == '-') f = -1;
 6     for ( ; isdigit(ch) ; ch = getchar()) x = x * 10 + ch - '0';
 7     return x * f;
 8 }
 9 const int fac[] = {1 , 1 , 2 , 6 , 24 , 120 , 720 , 5040 , 40320 , 362880};
10 const int aim = 24; 
11 const int maxCon = 362880;
12 bool vis[maxCon];
13 struct data {
14     int con[9];
15     int hashVal;
16     int step;
17 }_begin;
18 queue <data> Q;
19 int Cantor(int s[]) {
20     int sum = 0;
21     for (int i = 1 ; i <= 8 ; i ++) {
22         int cnt = 0;
23         for (int j = i + 1 ; j <= 8 ; j ++) {
24             if (s[i] > s[j]) {
25                 cnt ++;
26             }
27         }
28         sum += cnt * fac[8 - i];
29     }
30     return sum + 1;
31 }
32 int bfs() {
33     Q.push(_begin);
34     while (Q.size()) {
35         data _top = Q.front(); Q.pop();
36 
37         if (vis[_top.hashVal]) {
38             continue;
39         }
40         if (_top.hashVal == aim) {
41             return _top.step;
42         }
43         vis[_top.hashVal] = true;
44         _top.step ++;
45         data _next = _top;
46         for (int i = 1 ; i <= 4 ; i ++) {
47             swap(_next.con[i] , _next.con[i + 4]);
48         }
49         _next.hashVal = Cantor(_next.con);
50         Q.push(_next);
51         _next = _top;
52         int _up = _next.con[4] , _dwn = _next.con[8];
53         for (int i = 4 ; i >= 2 ; i --) {
54             _next.con[i] = _next.con[i - 1];
55             _next.con[i + 4] = _next.con[i + 3];
56         }
57         _next.con[1] = _up;
58         _next.con[5] = _dwn;
59         _next.hashVal = Cantor(_next.con);
60         Q.push(_next);
61         _next = _top;
62         int two = _next.con[2] , three = _next.con[3] , seven = _next.con[7] , six = _next.con[6];
63         _next.con[2] = six , _next.con[3] = two , _next.con[7] = three , _next.con[6] = seven;
64         _next.hashVal = Cantor(_next.con);
65         Q.push(_next);
66     }
67 }
68 
69 int main() {
70     for (int i = 1 ; i <= 8 ; i ++) {
71         _begin.con[i] = read();
72     }
73     _begin.hashVal = Cantor(_begin.con);
74     printf("%d\n" , bfs());
75 }

 

posted @ 2018-12-18 18:36  Richard_Yang  阅读(248)  评论(0编辑  收藏  举报