HDU:3336-Count the string(next数组理解)
2018-01-31 19:07
459 查看
Count the string
Time Limit: 2000/1000 MS (Java/Others)Memory Limit: 32768/32768 K (Java/Others)
Problem Description
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.
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), which is the length of string s. A line follows giving the string s. The characters in the strings are all lower-case letters.
Output
For each case, output only one number: the sum of the match times for all the prefixes of s mod 10007.Sample Input
14
abab
Sample Output
6解题心得:
题意就是给你一个字符串,问你字符串中和每个前缀匹配的子串有多少个,可以前缀和前缀自身匹配。
其实就是一个对于next数组的理解,next数组记录的就是当前字符为后缀匹配的前缀,所以很简单,直接next匹配的时候记录总数就可以了。
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<queue> #include<vector> #include<stack> #include<string> using namespace std; const int maxn = 2e5+100; const int MOD = 10007; char s[maxn]; int Next[maxn]; int cal_next(int n){ int ans = 1; int k = -1; Next[0] = -1; for(int i=1;i<n;i++){ ans++;//自身和自身匹配 ans %= MOD; while(k > -1 && s[k+1] != s[i]) k = Next[k]; if(s[k+1] == s[i]){ k++; ans++; ans %= MOD; } Next[i] = k; } return ans%MOD; } int main() { int t; scanf("%d",&t); while(t--){ int n; scanf("%d",&n); scanf("%s",s); int ans = cal_next(n); printf("%d\n",ans); } return 0; }
相关文章推荐
- Hdu 3336 Count the string[KMP next数组的理解]
- HDU 3336 Count the string (next数组活用)
- HDU 3336 Count the string(KMP算法next数组的应用)
- HDU 3336 Count the string(KMP+稍微DP+next数组的运用)
- HDU 3336 Count the string(kmp next数组的性质)
- HDU 3336 Count the string (KMP next数组运用——统计前缀出现次数)
- hdu 3336 Count the string(next数组)
- HDU - 3336 Count the string —— next数组求相同前缀后缀个数
- [KMP-NEXT数组特性]HDU 3336 Count the string
- HDU 3336 Count the string(KMP+Next数组递推)
- HDU 3336 Count the string(kmp数组)
- Count the string - HDU 3336(next+dp)
- HDU 3336 Count the string 后缀数组 或 (KMP + DP)
- Count the string HDU - 3336 (KMP next 不一样的用法(动态规划))
- HDU 3336 Count the string(KMP 理解)
- HDU3336-Count the string-KMP(next数组理解)
- [HDU 3336]Count the String[kmp][DP]
- hdu 3336 Count the string
- K - Count the string kmp_Next数组应用
- HDU 3336 Count the string 【KMP】【dp】