您的位置:首页 > 其它

HDU 3336 Count the string(KMP+稍微DP+next数组的运用)

2017-08-21 19:28 441 查看
It is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example: 

s: "abab" 

The prefixes are: "a", "ab", "aba", "abab" 

For each prefix, we can count the times it matches in s. So we can see that prefix "a" matches twice, "ab" matches twice too, "aba" matches once, and "abab" matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For "abab",
it is 2 + 2 + 1 + 1 = 6. 

The answer may be very large, so output the answer mod 10007. 

InputThe first line is a single integer T, indicating the number of test cases. 

For each case, the first line is an integer n (1 <= n <= 200000), which is the length of string s. A line follows giving the string s. The characters in the strin
4000
gs are all lower-case letters. 

OutputFor each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.
Sample Input
1
4
abab


Sample Output
6


题解:

给你一个长度为len的字符串问你他的所有前缀和是多少

比如abab

前缀a出现2次,ab出现2次,aba一次,abab一次所以是6

由于Next储存的是当前的后缀和前面的前缀的匹配情况,所以我们就稍微dp一下,对于每一个字符i,dp[i]=dp[next[i]]+1,就是当前前缀的次数,也就是说,当前的前缀等于前面那个前缀的出现次数+1

代码:

#include<algorithm>
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<math.h>
#include<string>
#include<stdio.h>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<deque>
using namespace std;
#define lson k*2
#define rson k*2+1
#define M (t[k].l+t[k].r)/2
#define INF 1008611111
#define ll long long
#define eps 1e-15
char T[200005];
int Next[200005];
int dp[200005];
void init()
{
int i=0,j=-1;
Next[0]=-1;
while(T[i])
{
if(j==-1||T[j]==T[i])
{
i++;
j++;
Next[i]=j;
}
else
j=Next[j];
}
}
int main()
{
int i,j,len,test;
int sum;
int N=10007;
scanf("%d",&test);
while(test--)
{
scanf("%d",&len);
scanf("%s",T);
init();
dp[0]=0;
dp[1]=1;
sum=0;
for(i=1;i<=len;i++)
{
dp[i]=(dp[Next[i]]+1)%N;
sum=(sum+dp[i])%N;
}
printf("%d\n",sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: