BZOJ 1079: [SCOI2008]着色方案 神奇的DP

来源:互联网 发布:免费psd源码社区 编辑:程序博客网 时间:2024/04/28 12:50

Description

  有n个木块排成一行,从左到右依次编号为1~n。你有k种颜色的油漆,其中第i种颜色的油漆足够涂ci个木块。
所有油漆刚好足够涂满所有木块,即c1+c2+…+ck=n。相邻两个木块涂相同色显得很难看,所以你希望统计任意两
个相邻木块颜色不同的着色方案。
Input

  第一行为一个正整数k,第二行包含k个整数c1, c2, … , ck。
Output

  输出一个整数,即方案总数模1,000,000,007的结果。
Sample Input
3

1 2 3
Sample Output
10
HINT

100%的数据满足:1 <= k <= 15, 1 <= ci <= 5
解题思路:
神奇的DP技巧,首先考虑一下直接状压是肯定不能通过的,复杂度是5^15,于是转换一下思路,我们记录使用1,2,3,4,5次的颜色有多少种,因为实际上不同种类的颜色之间是等价的,所以只需要记录出现的次数,因为考虑两种油漆如果当前都能涂x次,那么他们本质是一样的。所以我们用dp[a][b][c][d][e][last]记录还剩下1,2,3,4,5次使用次数的颜色的数量为a,b,c,d,e,上一次我们那的是使用次数剩余为last的颜色,那么这次在剩余last-1次的颜色中,我们只能少拿一次,因为不能拿相同的,这样转移就很容易的表示出来了。那么很容易推出转移式子,注意对于相邻位置不能是相同的颜色的设定,我们规定这次拿的等价颜色不能喝上次的等价颜色相同,于是直接在系数里面判断一下减去即可。。这个DP我完全不会,看了这位同学的博客理解了,多谢。OTZ

代码如下:

#include <bits/stdc++.h>using namespace std;const int mod = 1e9+7;int n, cnt[6];typedef long long LL;LL dp[16][16][16][16][16][6];LL dfs(int a, int b, int c, int d, int e, int last){    if(a + b + c + d + e == 0) return dp[a][b][c][d][e][last] = 1;    if(~dp[a][b][c][d][e][last]) return dp[a][b][c][d][e][last];    LL res = 0;    if(a > 0) res += (a - (last == 2)) * dfs(a - 1, b, c, d, e, 1), res %= mod;    if(b > 0) res += (b - (last == 3)) * dfs(a + 1, b - 1, c, d, e, 2), res %= mod;    if(c > 0) res += (c - (last == 4)) * dfs(a, b + 1, c - 1, d, e, 3), res %= mod;    if(d > 0) res += (d - (last == 5)) * dfs(a, b, c + 1, d - 1, e, 4), res %= mod;    if(e > 0) res += e * dfs(a, b, c, d + 1, e - 1, 5), res %= mod;    return dp[a][b][c][d][e][last] = res;}int main(){    scanf("%d", &n);    for(int i = 1; i <= n; i++){        int x;        scanf("%d", &x);        cnt[x]++;    }    memset(dp, -1, sizeof(dp));    LL ans = dfs(cnt[1], cnt[2], cnt[3], cnt[4], cnt[5], 0);    cout << ans << endl;    return 0;}
0 0
原创粉丝点击