Count the string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2871 Accepted Submission(s): 1332
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.
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.
1 4 abab
6求前缀出现的次数的总和。DP+kmp运用next[i]保存与以s[i]为后缀的串匹配的s的前缀的最大长度,换言之,next[i]-1表示与以s[i]为后缀的串匹配的s的前缀中最接近s[i]的位置。dp[i]代表以s[i]结尾的s的前缀(可以当成一个新的模式串)的前缀出现的次数总和。利用next[i]转移到匹配的位置,然后dp[i]=dp[next[i]-1]+1.AC代码:#include <iostream> #include <cstring> using namespace std; #define MAXN 200005 #define MOD 10007 int next[MAXN]; char s[MAXN]; int dp[MAXN]; int n; void get_next() { memset(next,0,sizeof(next)); for(int i = 1; i <n; i++) { int temp = next[i - 1]; while(temp && s[temp] != s[i]) temp = next[temp - 1]; if(s[temp] == s[i]) next[i] = temp + 1; else next[i] = 0; } } int main() { int t; cin>>t; while (t--) { cin>>n; cin>>s; get_next(); int sum=0; for(int i=0;i<n;i++) dp[i]=1; for(int i=0; i<n; i++) { if(next[i]) dp[i]+=dp[next[i]-1]; sum+=dp[i]; } cout<<sum%MOD<<endl; } return 0; }
5655




被折叠的 条评论
为什么被折叠?



