HDU3336 next数组性质

来源:互联网 发布:简述什么是波士顿矩阵 编辑:程序博客网 时间:2024/05/18 02:27

K - Count the string

 
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
14abab
Sample Output
6

注意next数组的性质    内在有联系
开一个res数组   维护ans表示res数组和   res初始化为0 1 1 1 ……(隐式初始化)

#include<iostream>#include<cstdio>#include<cstring>#include<vector>#include<algorithm>#include<map>#include<string>using namespace std;const int maxlen = 1000100;int n;int m;int arrnext[maxlen+1];int res[maxlen + 1];char mai[maxlen];char sub[maxlen];void getnext(){int i = 0;int j = -1;arrnext[0] = -1;int len = strlen(sub);while (i <= len){if (j == -1 || sub[i] == sub[j]){j++;i++;arrnext[i] = j;//if (i-arrnext[i] != i&&i%(i-arrnext[i]) == 0)//{//printf("%d %d\n", i, i / (i - arrnext[i]));//}}elsej = arrnext[j];}//printf("%d\n",len%(len - arrnext[len])==0?len/(len - arrnext[len]):1);}void kmp(){getnext();int ans = 0;int i = 0;int j = 0;int lenmai = strlen(mai);int lensub = strlen(sub);while (i < lenmai){while (i < lenmai&&j < lensub){if (j == -1 || mai[i] == sub[j]){i++;j++;}elsej = arrnext[j];}if (j == lensub){j = 0;ans++;}}//whileprintf("%d\n", ans);}int t;int main(){scanf("%d", &t);int key = 0;while (t--){int x;scanf("%d", &x);//if (x == 0)//break;key++;//scanf("%s",mai);scanf("%s", sub);//if (sub[0] == '.')//break;//printf("Test case #%d\n", key);//kmp();getnext();//printf("\n");int lensub = strlen(sub);//int ans = lensub - arrnext[lensub];//printf("%d\n", lensub%ans == 0 ? (lensub == ans ? ans : 0) : ans - (lensub%ans));int ans = 0;res[0] = 0;for (int i = 1;i <= lensub;i++){res[i] = 1 + res[arrnext[i]];res[i] %= 10007;ans += res[i];ans %= 10007;}printf("%d\n", ans);}return 0;}




原创粉丝点击