BZOJ 1079 [SCOI2008]着色方案 - 花式DP

從未見過DP還可以這樣玩的,一開始以爲是數學,C+容斥,後來覺得不對,哪有數學題長成這個樣的,然後各種dp,15維的dp實在是沒敢寫,於是膜了hzwer的代碼。。。真長見識。

考慮到c[i]的範圍不超過5,其中必有玄機,於是可以用5維表示還可以塗i塊木塊的顏色種數。因爲對於兩種均可以塗i塊的顏色,除了考慮與上一狀態不能重複以外,是完全等價的。排除上一狀態影響,則將當前狀態的轉移的貢獻減去一份即可。考慮到dp方程的轉移方向太過於複雜,用記憶化搜索會好一些。

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<algorithm>

using namespace std;

const int maxn=18;
const int mod=1000000007;

int n;
int c[maxn],num[maxn];
int dp[maxn][maxn][maxn][maxn][maxn][maxn];

int memorial_search(int a,int b,int c,int d,int e,int last)
{
    int &res=dp[a][b][c][d][e][last];
    if(res!=-1)return res;
    if(a+b+c+d+e==0)return res=1;
    res=0;
    if(a)
        res=(res+1LL*(a-(last==2))*memorial_search(a-1,b,c,d,e,1))%mod;
    if(b)
        res=(res+1LL*(b-(last==3))*memorial_search(a+1,b-1,c,d,e,2))%mod;
    if(c)
        res=(res+1LL*(c-(last==4))*memorial_search(a,b+1,c-1,d,e,3))%mod;
    if(d)
        res=(res+1LL*(d-(last==5))*memorial_search(a,b,c+1,d-1,e,4))%mod;
    if(e)
        res=(res+1LL*e*memorial_search(a,b,c,d+1,e-1,5))%mod;
    return res;
}
int main()
{
    memset(dp,-1,sizeof dp);
    scanf("%d",&n);
    for(int i=1,now;i<=n;i++)
        scanf("%d",&now),num[now]++;
    printf("%d",memorial_search(num[1],num[2],num[3],num[4],num[5],-1));
    return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章