BZOJ 1087 [SCOI2005]互不侵犯King(状压DP)

时间:2023-03-08 22:37:20

题意:在N×N的棋盘里面放K个国王,使他们互不攻击,共有多少种摆放方案。国王能攻击到它上下左右,以及左上
左下右上右下八个方向上附近的各一个格子,共8个格子。n<=9

思路:状压dp,dp[i][j][k]为前i行放了j个,第i行状态为k

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<vector>
#include<map>
#include<functional> #define fst first
#define sc second
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lc root<<1
#define rc root<<1|1
#define lowbit(x) ((x)&(-x)) using namespace std; typedef double db;
typedef long double ldb;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PI;
typedef pair<ll,ll> PLL; const db eps = 1e-;
const int mod = ;
const int maxn = 2e6+;
const int maxm = 2e6+;
const int inf = 0x3f3f3f3f;
const db pi = acos(-1.0); ll dp[][][];
int n, k;
int num[];
int ys[]; int main(){
mem(dp, );
mem(ys, );
scanf("%d %d", &n, &k);
for(int i = ; i < (<<n); i++){
int p = i;
int cnt = ;
while(p){
if(p&)cnt++;
p>>=;
}
num[i]=cnt;
}
for(int i = ; i < (<<n); i++){
if(((i<<)&i) ||((i>>)&i)){
continue;
}
ys[i] = ;
dp[][num[i]][i]=;
}
for(int i = ; i <= n; i++){
for(int j = ; j <= k; j++){
for(int p = ; p < (<<n); p++){//now
if(!ys[p])continue;
if(num[p]>j)continue;
for(int x = ; x < (<<n); x++){//last status from i-1
if(!ys[x])continue;
if((p&x)||((p<<)&x)||(p>>)&x)continue;
dp[i][j][p] += dp[i-][j-num[p]][x]; }
}
}
}
ll ans = ;
for(int i = ; i < (<<n); i++){
ans += dp[n][k][i];
}
printf("%lld", ans);
return ; }