【BZOJ1087】【SCOI2005】互不侵犯

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]就行了,最后加一个背包就行了。
#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值