【BZOJ1087 || SCOI2005】互不侵犯King

【题目描述】

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

 1 <=N <=9, 0 <= K <= N * N


【简要分析】

水题,大神请【Ctrl + W】

裸搜……咳咳,显然过不了

暴力dp也是可以过的

也容易想到用状态压缩去优化转移

然后最后再打个表,恭喜你,BZOJrank1非你莫属


有几个实现技巧

1. 把每个二级制数有多少个1用dp预处理出来(也可以用matrix67讲稿内的方法)

2. 把一行内国王的各种状态预处理出来

3. 利用位运算判断状态是否合法


【Code】

http://ideone.com/XAjBgR


#include <algorithm>
#include <ctime>
#include <cmath>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <cstdio>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <iostream>
 
using namespace std;
 
#define sci stack <int>
#define vci vector <int>
#define vcs vector <string>
#define vcd vector <double>
#define vci64 vector <long long>
 
const int maxn = 9 + 5;
const int maxk = 9 * 9 + 5;
 
typedef unsigned int uint;
typedef long long int64;
typedef unsigned long long uint64;
 
template <class T> inline T Sqr(const T & x) { return x * x; }
template <class T> inline T Abs(const T & x) { return x > 0 ? x : -x; }
template <class T> inline T Min(const T & a, const T & b) { return a < b ? a : b; }
template <class T> inline T Max(const T & a, const T & b) { return a > b ? a : b; }
template <class T> inline T Ksm(const T & a, const T & b, const T & m) { T _ = 1; for (; b; b >>= 1, a = a * a % m) (b & 1) ? _ = _ * a % m : 0; return _ % m; }
template <class T> inline void Swap(T & a, T & b) { T _; _ = a; a = b; b = _; }
 
int n, k, cn[1 << 9 + 1], cnt, state[1 << 9 + 1];
int64 f[maxn][maxk][1 << 9 + 1], ans;
 
void dfs(int wid, int sta)
{
   if (wid == n) return state[++cnt] = sta, (void) 0;
   if (dfs(wid + 1, sta << 1), !(sta & 1)) dfs(wid + 1, sta << 1 | 1);
}
 
bool check(int a, int b) { return !(a & b) && !((a << 1) & b) && !((a >> 1) & b); }
 
int main()
{
 
   scanf("%d%d", &n, &k), dfs(0, 0);
   for (int i = 1; i <= (1 << n) - 1; ++i)
      cn[i] = cn[i / 2] + (i & 1);
   f[0][0][1] = 1;
   for (int i = 1; i <= n; ++i)
      for (int j = 0; j <= k; ++j)
         for (int li = 1; li <= cnt; ++li)
            for (int ru = 1; ru <= cnt; ++ru)
               if ((j >= cn[state[ru]]) && (check(state[li], state[ru])))
                  f[i][j][ru] += f[i - 1][j - cn[state[ru]]][li];
   for (int i = 1; i <= cnt; ++i) ans += f[n][k][i];
   printf("%lld", ans);
 
   return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值