您的位置:首页 > 其它

hdu 3336 Count the string (kmp + dp)

2016-05-12 19:01 507 查看
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
;
int Next
, dp
, 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: