您的位置:首页 > 其它

HDU 3336 Count the String(KMP+DP)

2017-01-30 10:47 363 查看
http://acm.hdu.edu.cn/showproblem.php?pid=3336

题意:给出一个字符串,计算所有前缀在字符串中出现的次数。

思路:考虑KMP的next[]来解题。next[i]=j表示最大的j使得0~j==i-j~i。

对于样例的next[]分析如下:

0 1 2 3

a[] a b a b

next[] -1 0 0 1

dp[i]表示子串a[0~i]共含有以a[i]为结尾的前缀的数目,则以a[i]结尾的前缀数就是自己本身加上以a[next[i]]结尾的前缀数,即dp[next[i]]。

#include<iostream>
#include<cstring>
using namespace std;

const int maxn = 200000 + 5;

int n;

char a[maxn];
int next[maxn];
int dp[maxn];

void get_next()
{
int i = -1, j = 0;
::next[0] = -1;
int l = strlen(a);
while (j < l)
{
if (i == -1 || a[i] == a[j])
::next[++j] = ++i;
else
i = ::next[i];
}
}

int main()
{
//freopen("D:\\txt.txt", "r", stdin);
int t;
cin >> t;
while (t--)
{
cin >> n;
cin >> a;
get_next();
memset(dp, 1, sizeof(dp));
dp[0] = 0;
int sum = 0;
for (int i = 1; i <= n; i++)
{
dp[i] = dp[::next[i]] + 1;
sum += dp[i] % 10007;
}
cout << sum % 10007 << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: