hdu 3336 Count the string (kmp + dp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w144215160044/article/details/51386635

http://acm.hdu.edu.cn/showproblem.php?pid=3336

题意:给出一个长度为n的字符串,求出该字符串的所有前缀出现的总次数

思路:kmp求出该字符串的next数组,第i个位置dp[i]可有dp[next[i]]+1得到

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

using namespace std;

#define N 1100000
#define met(a, b) memset(a, b, sizeof(a))

const double PI = acos(-1.0);

typedef long long LL;

char str[N];
int Next[N], dp[N], len;

void Get_Next ()
{
    int i = 0, j = -1;
    Next[i] = j;

    while (i<len)
    {
        if (j==-1 || str[i] == str[j])
            Next[++i] = ++j;
        else j = Next[j];
    }
}

int main ()
{
    int t, n;
    scanf ("%d", &t);

    while (t--)
    {
        met (str, 0);
        met (dp, 0);
        met (Next, 0);

        scanf ("%d%s", &n, str);

        len = strlen(str);
        Get_Next ();

        int ans = 0;

        for (int i=1; i<=len; i++)
        {
            dp[i] = dp[ Next[i] ] + 1;
            ans += dp[i];
            ans %= 10007;
        }
        printf ("%d\n", ans);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/w144215160044/article/details/51386635