lightoj 1061

摘要:
暴力的状态压缩

正文:

题意:给出8*8格子,里面有8个皇后,其余全为空格,要求移动最少步数,使其互相都不会攻击。

想了好久,打了个表,发现8皇后满足的条件只有92个,暴力感觉也可以接受,但是在距离那里有点难想,dp[i][s]代表已经移动了原来棋盘的前i个皇后,s中置为1的表示要求目标皇后位置已经到达的状态。如果移动原来的皇后到某个位置,然而这个位置已经被占了,其实可以用物理里面碰撞的思想,把它们交换一下,就等价了,距离仍然是曼哈顿距离。

之后就是对92种状态每种都求一次状压,92 256 256,可以接受。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<utility>
#include<sstream>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int inf = 0x3f3f3f3f;
const int maxn = 1005;
int a[100],tot = 0;
int dp[11][500];
char s[10][10];
vector<P>vt[100],st;
bool leap[100];
bool check(){
for(int i = 0;i < 8;i++){
for(int j = i + 1;j < 8;j++){
int temp1 = j - i;
int temp2 = a[j] - a[i];
if(abs(temp1) == abs(temp2))
return false;
}
}
return true;
}
void prin(){
for(int i = 0;i < 8;i++)
vt[tot].push_back(P(i,a[i]));
tot++;
}
void dfs(int x){
if(x == 8){
if(check())prin();
return;
}
for(int i = 0;i < 8;i++){
if(leap[i])continue;
leap[i] = true;
a[x] = i;
dfs(x + 1);
leap[i] = false;
}
}
int getdis(int id,int x,int y){
int tempx = abs(vt[id][x].first - st[y].first);
int tempy = abs(vt[id][x].second - st[y].second);
if(tempx == 0 && tempy == 0)return 0;
if(tempx == 0)return 1;
if(tempy == 0)return 1;
if(tempx == tempy)return 1;
return 2;
}
int work(int id){
for(int i = 0;i <= 9;i++)
for(int j = 0;j <= 300;j++)
dp[i][j] = inf;
dp[0][0] = 0;
for(int i = 0;i < 8;i++){
for(int s = 0;s < (1 << 8);s++){
if(dp[i][s] == inf)continue;
for(int j = 0;j < 8;j++){
if((s >> j)&1)continue;
int now = s | (1 << j);
dp[i + 1][now] = min(dp[i + 1][now],dp[i][s] + getdis(id,i,j));
}
}
}
return dp[8][255];
}
int main()
{

#ifdef LOCAL
freopen("C:\\Users\\ΡΡ\\Desktop\\in.txt","r",stdin);
//freopen("C:\\Users\\ΡΡ\\Desktop\\out.txt","w",stdout);
#endif // LOCAL
memset(leap,false,sizeof(leap));
dfs(0);
int t,kase = 1;
scanf("%d",&t);
while(t--){
st.clear();
for(int i = 0;i < 8;i++)
scanf("%s",s + i);
for(int i = 0;i < 8;i++){
for(int j = 0;j < 8;j++){
if(s[i][j] == 'q')
st.push_back(P(i,j));
}
}
int ans = inf;
for(int i = 0;i < 92;i++){
ans = min(ans,work(i));
}
printf("Case %d: %d\n",kase++,ans);
}
return 0;
}