Description
在N×N的棋盘里面放K个国王,使他们互不攻击,共有多少种摆放方案。国王能攻击到它上下左右,以及左上左下右上右下八个方向上附近的各一个格子,共8个格子。
Input
只有一行,包含两个数N,K ( 1 <=N <=9, 0 <= K <= N * N)
Output
方案数。
Sample Input
3 2
Sample Output
16
题解
典型的状压dp.
先用dfs求出所有满足条件的状态,然后判断st[j]&st[p]和st[j]>>1&st[p]和st[j]<<1&st[p]就行了,最后加一个背包就行了。
题解
典型的状压dp.
先用dfs求出所有满足条件的状态,然后判断st[j]&st[p]和st[j]>>1&st[p]和st[j]<<1&st[p]就行了,最后加一个背包就行了。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
ll dp[20][100][1<<10];
int st[1<<10],c[1<<10],n,k,cnt;
void dfs(int shu,int sum,int pos){
if(pos>=n){
st[++cnt]=shu;
c[cnt]=sum;
return ;
}
dfs(shu|(1<<pos),sum+1,pos+2);
dfs(shu,sum,pos+1);
}
int main()
{
scanf("%d%d",&n,&k);
dfs(0,0,0);
for(int i=1;i<=cnt;i++){
dp[1][i][c[i]]=1ll;
}
for(int i=2;i<=n;i++){
for(int j=1;j<=cnt;j++){
for(int p=1;p<=cnt;p++){
if(st[j]&st[p]) continue;
if((st[j]<<1)&st[p]) continue;
if((st[j]>>1)&st[p]) continue;
for(int q=k;q>=c[j];q--)
dp[i][j][q]+=dp[i-1][p][q-c[j]];
}
}
}
ll ans=0;
for(int i=1;i<=cnt;i++)
ans+=dp[n][i][k];
printf("%lld\n",ans);
return 0;
}