After solving nice problems about bishops and rooks, Petya decided that he would like to learn to play chess. He started to learn the rules and found out that the most important piece in the game is the king.
The king can move to any adjacent cell (there are up to eight such cells). Thus, two kings are in the attacking position, if they are located on the adjacent cells.
Of course, the first thing Petya wants to know is the number of ways one can position k kings on a chessboard of size n × n so that no two of them are in the attacking position. Help him!
The king can move to any adjacent cell (there are up to eight such cells). Thus, two kings are in the attacking position, if they are located on the adjacent cells.
Of course, the first thing Petya wants to know is the number of ways one can position k kings on a chessboard of size n × n so that no two of them are in the attacking position. Help him!
Input
The input file contains two integers n (1 ≤ n ≤ 10) and k (0 ≤ k ≤ n 2).
Output
Print a line containing the total number of ways one can put the given number of kings on a chessboard of the given size so that no two of them are in attacking positions.
Sample test(s)
Input
Test #1 3 2 Test #2 4 4
Output
Test #1
16
Test #2
79
16
Test #2
79
解题思路:状压DP经典题目, dp[i][j][k]表示第i行的状态为j且前i行总共放置了k个棋子的方案数,则不难得出下面的状态转移方程。
dp[0][0][0] = 1;
dp[i][j][k] = sigma(dp[i-1][p][k-cj]),其中p为上一行的状态且p和j不互相冲突,cj为状态j包含的1的个数。
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
typedef long long ll;
ll dp[11][(1<<10)+10][105];
int s[(1<<10)+10], scnt;
int bitcnt[(1<<10)+10];
int N, K;
bool check_state(int x) {
int bit[11], bcnt = 0;
if(x == 0) bit[bcnt++] = 0;
while(x) {
bit[bcnt++] = x&1;
x >>= 1;
}
for(int i = 0; i < bcnt; ++i) {
int t = 0;
if(i - 1 >= 0) t += bit[i-1];
t += bit[i];
if(i + 1 < bcnt) t += bit[i+1];
if(bit[i] && t > 1) return false;
}
return true;
}
int count_bit(int x) {
int bit = 0;
while(x) {
if(x&1) bit++;
x >>= 1;
}
return bit;
}
void init() {
scnt = 0;
for(int i = 0; i < (1<<N); ++i) {
if(check_state(i)) {
s[scnt++] = i;
}
bitcnt[i] = count_bit(i);
}
}
int main() {
//freopen("aa.in", "r", stdin);
while(scanf("%d %d", &N, &K) != EOF) {
init();
dp[0][0][0] = 1;
for(int i = 1; i <= N; ++i) {
for(int j = 0; j < scnt; ++j) {
for(int k = 0; k <= K; ++k) {
dp[i][s[j]][k] = 0;
if(bitcnt[s[j]] > k) continue;
for(int l = 0; l < scnt; ++l) {
int t1 = s[j] & s[l];
int t2 = s[j] | s[l];
if(t1 == 0 && check_state(t2)) {
dp[i][s[j]][k] += dp[i-1][s[l]][k-bitcnt[s[j]]];
}
}
}
}
}
ll ans = 0;
for(int i = 0; i < scnt; ++i) {
ans += dp[N][s[i]][K];
}
cout << ans << endl;
}
return 0;
}