HDOJ 5677 ztr loves substring (Manacher+背包型DP)

题意

问能不能从给出的字符串中找到k个回文子串能组成总长度为l的串。

思路

先Manacher预处理出所有长度的回文串的个数,然后就变成一个多重背包了,即dp[i][j][l]表示枚举到长度为i的回文串时已经取了j个串总长度为l的情况是否存在,因为长度为i的回文串有很多,一个一个枚举肯定就T了,我们就用多重背包那种做法把数量变成二进制来处理就行了,总复杂度 LKK)log(cnt[i])
马拉车的时候str数组忘了开两倍wa了n次。。。mdzz

代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define LL long long
#define Lowbit(x) ((x)&(-x))
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1|1
#define MP(a, b) make_pair(a, b)
const int INF = 0x3f3f3f3f;
const int MOD = 1000000007;
const int maxn = 1e5 + 10;
const double eps = 1e-8;
const double PI = acos(-1.0);
typedef pair<int, int> pii;
char s[210], str[210];
int cnt[210], p[210];
int dp[2][110][110];

void Manacher(int len)
{
    int mx = 0, id = 0;
    for (int i = 0; i < len; i++)
    {
        if (mx > i) p[i] = min(p[2*id-i], mx - i);
        else p[i] = 1;
        while (str[i-p[i]] == str[i+p[i]]) p[i]++;
        if (p[i] + i > mx)
            mx = i + p[i], id = i;
    }

}

int init()
{
    int len = strlen(s);
    int l = 0;
    str[l++] = '$';
    str[l++] = '#';
    for (int i = 0; i < len; i++)
    {
        str[l++] = s[i];
        str[l++] = '#';
    }
    str[l] = 0;
    return l;
}

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int T;
    cin >> T;
    while (T--)
    {
        int n, K, L;
        scanf("%d%d%d", &n, &K, &L);
        memset(cnt, 0, sizeof(cnt));
        for (int i = 0; i < n; i++)
        {
            scanf("%s", s);
            int len = init();
            Manacher(len);
            //for (int j = 0; j < len; j++) printf("%d %d %c %d\n", i, j, str[j], p[j]);
            for (int j = 0; j < len; j++)
                if (p[j] > 1) cnt[p[j]-1]++;
        }
        for (int i = L; i > 0; i--)
            cnt[i] += cnt[i+2];
        memset(dp, 0, sizeof(dp));
        int now = 0, la = 1;
        dp[0][0][0] = 1;
        for (int i = 1; i <= L; i++)
        {
            now ^= 1;
            memset(dp[now], 0, sizeof(dp[now]));
            for (int j = 0; j <= K; j++)
                for (int o = 0; o <= L; o++)
                    for (int num = 0; num <= cnt[i] && num + j <= K && num * i + o <= L; num++)
                        dp[now][num+j][num*i+o] |= dp[now^1][j][o];
        }
        puts(dp[now][K][L] ? "True" : "False");
    }
    return 0;
}

你可能感兴趣的:(dp)