HDU 6030 Happy Necklace (DP)

Little Q wants to buy a necklace for his girlfriend. Necklaces are single strings composed of multiple red and blue beads.
Little Q desperately wants to impress his girlfriend, he knows that she will like the necklace only if for every prime length continuous subsequence in the necklace, the number of red beads is not less than the number of blue beads.
Now Little Q wants to buy a necklace with exactly n beads. He wants to know the number of different necklaces that can make his girlfriend happy. Please write a program to help Little Q. Since the answer may be very large, please print the answer modulo 109+7.
Note: The necklace is a single string, {not a circle}.

题意

对于一个串(仅包含 0 和 1 两种状态),要求任意素数长度的子串(不是子序列),满足 1 的个数大于等于 0 的个数

问若串长为 n ,能构造出多少满足条件的串?

解题思路

对于素数 2 ,串中 0 的出现至少应满足 01 交替,不能同时出现 00 。

对于素数 3 ,串中 0 的出现至少应满足 0110110 交替,即两个 0 之间至少应间隔两个 1 。

对于素数 5, 7, 11… ,在满足素数 3 所提出的条件下,均能够达到要求。

dp[i][j][k] 表示串长为 1< ,串中首个 0 到串首距离为 j ,串中末个 0 到串尾距离为 k 。例如,串 01111101 属于 dp[3][0][1]

对于串的拼接,结合对素数判断的要求,故 0j,k2 。例如,串 11101111 属于 dp[3][2][2]

状态转移为 dp[i][j][k] = dp[i-1][j][kk] * dp[i-1][jj][k] if jj+kk>=2

在预处理出所有 1< 串长的情况后,对于 n=2a1+2a2+...+2am ,其解即为上述解的合并。

代码

#include
using namespace std;
const int mod = 1e9 + 7;
long long n, dp[64][3][3], ans[2][3][3];
void init()
{
    memset(dp, 0, sizeof(dp));
    dp[0][2][2] = 1;
    dp[1][2][2] = 1;
    dp[1][1][0] = 1;
    dp[1][0][1] = 1;
    for(int i=2;i<=63;i++)
    for(int j=0;j<=2;j++)
    for(int k=0;k<=2;k++)
    for(int jj=0;jj<=2;jj++)
    for(int kk=0;kk<=2;kk++)
        if(jj + kk >= 2)
            (dp[i][j][k] += dp[i-1][j][kk] * dp[i-1][jj][k]) %= mod;
}
int main()
{
    init();
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%I64d", &n);
        memset(ans, 0, sizeof(ans));
        dp[0][0][0] = 1;
        int cas = 0;
        bool flg = 1;
        for(int i=0;n;n/=2,i++)
        {
            if(n%2==0)  continue;
            if(flg) {
                for(int j=0;j<=2;j++)
                for(int k=0;k<=2;k++)
                    ans[cas][j][k] = dp[i][j][k];
                cas = 1 - cas;
                flg = false;
                continue;
            }
            for(int j=0;j<=2;j++)
                for(int k=0;k<=2;k++)
                {
                    ans[cas][j][k] = 0;
                    for(int jj=0;jj<=2;jj++)
                        for(int kk=0;kk<=2;kk++)
                            if(jj+kk>=2)
                                (ans[cas][j][k] += ans[1-cas][j][kk] * dp[i][jj][k]) %= mod;
                }
            cas = 1-cas;
        }
        long long fin = 0;
        for(int j=0;j<=2;j++)
        for(int k=0;k<=2;k++)
            (fin += ans[1-cas][j][k]) %= mod;
        printf("%I64d\n", fin);
    }
}

你可能感兴趣的:(HDU,dp)