P1896 [SCOI2005]互不侵犯(状压DP)

题目

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

题解

f [ i ] [ j ] [ k ] f[i][j][k] f[i][j][k]为第 i i i行,状态为 j j j,国王数为 k k k时的方案数
可以先预处理出所有合法的状态
h [ i ] h[i] h[i]表示每种状态, g [ i ] g[i] g[i]表示每种状态下国王的个数
判断状态可以转移的方法

if (h[j] & h[l]) continue;  // 上下可以攻击到 
if (h[j] & (h[l] << 1)) continue; // 右上角
if ((h[j] << 1) & h[l]) continue; // 左上角

code

#include <bits/stdc++.h>
using namespace std;  
typedef long long LL;  

template <typename T> 
inline void read(T &s) {
	s = 0;
	T w = 1, ch = getchar(); 
	while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
	while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
	s *= w; 
}

LL n, k, cnt, ans;
LL h[1000], g[1000];  
LL f[10][1000][90]; 

int main() {
	read(n); read(k); 
	
	for (int i = 0; i < (1 << n); ++i) {
		if (!(i & (i << 1)) && !(i & (i >> 1))) {
			h[++cnt] = i; 
			
			int t = i; 
			while (t)
				g[cnt] += t & 1, t >>= 1; 
		}
	}
	for (int i = 1; i <= cnt; ++i)
		if (g[i] <= k)
			f[1][i][ g[i] ] = 1; 
	
	for (int i = 2; i <= n; ++i) {
		for (int j = 1; j <= cnt; ++j) {
			for (int l = 1; l <= cnt; ++l) {
				if (h[j] & h[l]) continue; 
				if (h[j] & (h[l] << 1)) continue; 
				if ((h[j] << 1) & h[l]) continue; 
				
				for (int o = 1; o <= k; ++o) {
					if (g[j] + o > k) continue; 
					f[i][j][ g[j] + o] += f[i - 1][l][o]; 
				}
			}
		}	
	}
	
	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= cnt; ++j)
			ans += f[i][j][k]; 
	
	printf("%lld\n", ans); 
	return 0; 
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值