HDU 4529 郑厂长系列故事——N骑士问题 状压dp
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=4529
郑厂长系列故事——N骑士问题
Memory Limit: 65535/32768 K (Java/Others)
题意
在摆了8个八皇后的8*8的棋盘上摆放n个骑士,要求任意两个骑士互不攻击的方案数。
题解
dp[cur][v][i][j]表示第cur行状态是j,第cur-1行状态是i,摆放了v个骑士的方案数。
代码
#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<ctime>
#include<vector>
#include<cstdio>
#include<string>
#include<bitset>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
#define X first
#define Y second
#define mkp make_pair
#define lson (o<<1)
#define rson ((o<<1)|1)
#define mid (l+(r-l)/2)
#define sz() size()
#define pb(v) push_back(v)
#define all(o) (o).begin(),(o).end()
#define clr(a,v) memset(a,v,sizeof(a))
#define bug(a) cout<<#a<<" = "<<a<<endl
#define rep(i,a,b) for(int i=a;i<(b);i++)
#define scf scanf
#define prf printf
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
typedef vector<pair<int,int> > VPII;
const int INF=0x3f3f3f3f;
const LL INFL=10000000000000000LL;
const double eps=1e-9;
const double PI = acos(-1.0);
//start----------------------------------------------------------------------
const int maxm=8;
LL dp[2][11][1<<maxm][1<<maxm];
int sumv[1<<8];
bool f1[1<<maxm][1<<maxm];
bool f2[1<<maxm][1<<maxm];
int arr[maxm];
int n;
void pre(){
clr(sumv,0);
clr(f1,0);
clr(f2,0);
rep(i,0,(1<<maxm)){
rep(j,0,maxm) if(i&(1<<j)){
sumv[i]++;
}
rep(j,0,(1<<maxm)){
if(i&(j<<2)||i&(j>>2)) f1[i][j]=true;
if(i&(j<<1)||i&(j>>1)) f2[i][j]=true;
}
}
}
char str[22];
int main() {
pre();
int tc;
scf("%d",&tc);
while(tc--){
scf("%d",&n);
clr(arr,0);
for(int i=0;i<maxm;i++){
scf("%s",str);
rep(j,0,maxm){
if(str[j]=='*') arr[i]|=(1<<j);
}
}
int pre=0,cur=1;
clr(dp[cur],0);
for(int i=0;i<(1<<maxm);i++){
if(i&arr[0]) continue;
for(int j=0;j<(1<<maxm);j++){
if(j&arr[1]) continue;
if(f1[i][j]) continue;
if(sumv[i]+sumv[j]>n) continue;
dp[cur][sumv[i]+sumv[j]][i][j]++;
}
}
for(int t=2;t<maxm;t++){
swap(pre,cur);
clr(dp[cur],0);
for(int k=0;k<(1<<maxm);k++){
if(k&arr[t]) continue;
for(int j=0;j<(1<<maxm);j++){
if(j&arr[t-1]) continue;
if(f1[j][k]) continue;
for(int i=0;i<(1<<maxm);i++){
if(i&arr[t-2]) continue;
if(f1[i][j]||f2[i][k]) continue;
int w=sumv[k];
for(int v=w;v<=n;v++){
dp[cur][v][j][k]+=dp[pre][v-w][i][j];
}
}
}
}
}
LL ans=0;
for(int i=0;i<(1<<maxm);i++){
for(int j=0;j<(1<<maxm);j++){
ans+=dp[cur][n][i][j];
}
}
prf("%lld\n",ans);
}
return 0;
}
//end-----------------------------------------------------------------------