Count the string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3132 Accepted Submission(s): 1458
Problem DescriptionIt 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 strings 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
14abab
Sample Output
6
題目大意:給你一個串,統計這個串所有的首碼在串中出現的次數,然後模上100007. 解題思路:乍一看,還真的不知道如何分析。將問題分解成以a[i]結束的子串包含的首碼,然後dp,即可求出。具體思路見代碼中有詳解。
題目地址:Count the string
AC代碼:
/* next[j]=i, dp[j]=dp[i]+1; 以i為最後一個字母首碼有dp[i]個,則以j為最後一個字母首碼有dp[i]+1個,加一個本身. 下面是一個例子: a b a b c a b a b c d next[i] 0 0 1 2 0 1 2 3 4 5 0 dp[i] 1 1 2 2 1 2 2 3 3 2 1 設dp[i]:以a[i]結尾的子串總共含首碼的數量*/#include<iostream>#include<cstring>#include<string>#include<cstdio>#define MO 10007using namespace std;int len,next[200005],dp[200005],res;char a[200005];void getnext(){ int i,j; next[0]=0,next[1]=0; for(i=1;i<len;i++) { j=next[i]; while(j&&a[i]!=a[j]) j=next[j]; if(a[i]==a[j]) next[i+1]=j+1; else next[i+1]=0; }}int main(){ int T,i; scanf("%d",&T); while(T--) { scanf("%d%s",&len,a); getnext(); memset(dp,0,sizeof(dp)); res=0; for(i=1;i<=len;i++) { dp[i]=dp[next[i]]+1; res=(res+dp[i])%MO; } cout<<res<<endl; } return 0;}/*311ababcababcd*/