HDOJ 3336 Count the string

来源:互联网 发布:cetv4 网络回看 编辑:程序博客网 时间:2024/06/06 06:15

Count the string

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit:32768/32768 K (Java/Others)
Total Submission(s): 10124    Accepted Submission(s): 4733

Problem Description

It is well known that AekdyCoin is good at string problems as well as numbertheory problems. When given a string s, we can write down all the non-emptyprefixes 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 thatprefix "a" matches twice, "ab" matches twice too,"aba" matches once, and "abab" matches once. Now you areasked 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.

 

 

Input

The 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), whichis the length of string s. A line follows giving the string s. The charactersin the strings are all lower-case letters.

 

 

Output

Foreach case, output only one number: the sum of the match times for all theprefixes of s mod 10007.

 

 

Sample Input

1

4

abab

 

 

Sample Output

6


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

思路:还是对KMP中next数组的运用,再用点DP的思想。

          我们用dp[i]表示以s[i]结尾的字符串含有的前缀数量

          状态转移方程为dp[i]=dp[next[i]]+1   即长度小于i 的前缀数量+长度为i 的前缀(1)


#include <bits/stdc++.h>using namespace std;#define mst(a,b) memset((a),(b),sizeof(a))#define f(i,a,b) for(int i=(a);i<(b);++i)typedef long long ll;const int maxn= 200005;const int mod = 10007;const ll INF = 0x3f3f3f3f;const double eps = 1e-6;#define rush() int T;scanf("%d",&T);while(T--)int n;char s[maxn];int nex[maxn];int dp[maxn];void getnext(){    int i=0,j=-1;    nex[0]=-1;    while(i<n)    {        if(j==-1||s[i]==s[j])            nex[++i]=++j;        else j=nex[j];    }}void solve(){    getnext();    mst(dp,0);    int sum=0;    for(int i=1;i<=n;i++)    {        dp[i]=dp[nex[i]]+1;        sum=(sum+dp[i])%mod;    }    printf("%d\n",sum);}int main(){    rush()    {        scanf("%d",&n);        scanf("%s",s);        solve();    }    return 0;}


原创粉丝点击