洛谷P1896 [SCOI2005]互不侵犯King

链接

  https://www.luogu.org/problem/show?pid=2051

题解

  经典状压DP题,f[i][j][k]表示已经做了i行,放了j个国王,当前行的状态是k。
  转移的时候直接枚举上一行和当前行的状态转移就行了。

代码

//状压dp
#include <cstdio>
#include <algorithm>
#define maxn 10
#define ll long long
using namespace std;
ll N, K, s[1<<maxn], f[maxn][100][1<<maxn];
void dfs(ll pos, ll x)
{
    if(pos==N){s[++s[0]]=x;return;}
    dfs(pos+1,x);
    if((x&(1<<pos-1))==0)dfs(pos+1,x|(1<<pos));
}
bool check(ll x, ll y)
{
    if(x&y)return false;
    for(ll t=x|y;t;t>>=1)if((t&1) and (t&2))return false;
    return true;
}
ll cnt(ll x)
{
    ll cnt=0;
    for(;x;x>>=1)cnt+=x&1;
    return cnt;
}
int main()
{
    ll i, j, f1, f2, ans=0;
    scanf("%lld%lld",&N,&K);
    dfs(0,0);
    f[0][0][1]=1;
    for(i=1;i<=N;i++)
    {
        for(j=0;j<=K;j++)
        {
            for(f1=1;f1<=s[0];f1++)
            {
                for(f2=1;f2<=s[0];f2++)
                {
                    if(check(s[f1],s[f2])==false or cnt(s[f1]|s[f2])>j)continue;
                    f[i][j][f2]+=f[i-1][j-cnt(s[f2])][f1];
                }
            }
        }
    }
    for(i=1;i<=s[0];i++)ans+=f[N][K][i];
    printf("%lld\n",ans);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值