着色方案(状压dp)

题目链接:[SCOI2008]着色方案

题意:

  1. 有n个木块排成一行,从左到右依次编号为1~n。你有k种颜色的油漆,其中第i种颜色的油漆足够涂ci个木块。所有油漆刚好足够涂满所有木块,即c1+c2+…+ck=n。相邻两个木块涂相同色显得很难看,所以你希望统计任意两个相邻木块颜色不同的着色方案。
  2. 第一行为一个正整数k,第二行包含k个整数c1, c2, … , ck。
  3. 输出一个整数,即方案总数模1,000,000,007的结果。
  4. 1 <= k <= 15, 1 <= ci <= 5

思路:(转自学长博客[SCOI2008]着色方案 (状态压缩))
5. 首先,这显然是一道dp题目,然后开始考虑dp状态的设定。
6. 对于每个位置的选择,我们需要知道:一,到当前位置时颜色的剩余状态。二,前一个位置涂得颜色。
7. 颜色的剩余状态假如强行记录的话,共有15种颜色,每种颜色有5次填涂,状态数总共是5^15。
8. 我们发现,并不一定确切的知道每一种颜色的剩余状态,可以通过将颜色归类,来减少状态数,这里需要保证的是同类颜色的处理和对答案的影响完全一致。
9. 可以通过颜色的剩余填涂次数,将所有颜色分为5类,分别对应剩余1次、2次、3次、4次、5次。每一类的容量最大为15,状态数为15^5。

ysx大佬的博客对代码解释的很好了 —> 着色方案(状压DP)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<set>
#define inf 0x3f3f3f3f3f3f3f3f
using namespace std;

typedef long long ll;

const int N = 2e5+10;
const ll mod = 1e9+7;

int vis[N];
ll dp[16][16][16][16][16][6];

ll dfs(int a, int b, int c, int d, int e, int pre)
{
    if(dp[a][b][c][d][e][pre] != -1) return dp[a][b][c][d][e][pre];
    if(a+b+c+d+e == 0) return dp[a][b][c][d][e][pre] = 1;
    ll ans = 0;
    if(a > 0)
    {
        ans += (a-(pre == 2))*dfs(a-1, b, c, d, e, 1);
        ans %= mod;
    }
    if(b > 0)
    {
        ans += (b-(pre == 3))*dfs(a+1, b-1, c, d, e, 2);
        ans %= mod;
    }
    if(c > 0)
    {
        ans += (c-(pre == 4))*dfs(a, b+1, c-1, d, e, 3);
        ans %= mod;
    }
    if(d > 0)
    {
        ans += (d-(pre == 5))*dfs(a, b, c+1, d-1, e, 4);
        ans %= mod;
    }
    if(e > 0)
    {
        ans += e*dfs(a, b, c, d+1, e-1, 5);
        ans %= mod;
    }
    return dp[a][b][c][d][e][pre] = ans%mod;
}

int main()
{
    int n,x;
    memset(dp, -1, sizeof(dp));
    cin >> n;
    for(int i = 0; i < n; i++)
    {
        cin >> x;
        vis[x]++;
    }
    cout << dfs(vis[1], vis[2], vis[3], vis[4], vis[5], 0);
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值