procedure2012
It's not worth it to know you're not worth it!

[关键字]:搜索 位运算

[题目大意]:在一个n*n的棋盘里放k个王后,问使它们不能互相攻击的摆放方案有多少种。

//==================================================================

[分析]:就是n皇后问题的稍微变形,但要加上位运算优化。具体可以看matrix67神牛的博文。

[代码]:

View Code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;

int n,m,goal;
int ans,sum;

void DFS(int row,int ld,int rd,int sum,int now)
{
if (now>n) return;
if (sum<m)
{ int pos=goal&(~(row|ld|rd));
//printf("%d %d %d %d\n",pos,row,ld,rd);
while (pos>0)
{
int p=pos&(-pos);
pos-=p;
DFS(row+p,(ld+p)<<1,(rd+p)>>1,sum+1,now+1);
}
DFS(row,ld<<1,rd>>1,sum,now+1);
}
else ++ans;
}

int main()
{
scanf("%d%d",&n,&m);
goal=(1<<n)-1;
//printf("%d\n",goal);
DFS(0,0,0,0,0);
printf("%d\n",ans);
system("pause");
return 0;
}



posted on 2012-03-24 22:10  procedure2012  阅读(173)  评论(0编辑  收藏  举报