标签:des style io os ar for div sp on
1 4 abab
6 题意:求串的前缀在串中出现的次数 思路:KMP的next[]数组的应用,处理完next[]数组后,则以第i个字母为结尾的串中出现前缀的个数就是本身加上dp[next[i]]的结果,因为我们知道next[i]数组代表的是 和前缀匹配的长度,所以可以归纳到前缀中#include <iostream> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; const int maxn = 200005; const int mod = 10007; int dp[maxn], next[maxn], n; char pattern[maxn]; int getNext() { int m = strlen(pattern); next[0] = next[1] = 0; for (int i = 1; i < m; i++) { int j = next[i]; while (j && pattern[i] != pattern[j]) j = next[j]; next[i+1] = pattern[i] == pattern[j] ? j+1 : 0; } memset(dp, 0, sizeof(dp)); int sum = 0; for (int i = 1; i <= n; i++) { dp[i] = (dp[next[i]] + 1) % mod; sum = (sum + dp[i]) % mod; } return sum; } int main() { int t; scanf("%d", &t); while (t--) { scanf("%d", &n); scanf("%s", pattern); printf("%d\n", getNext()); } return 0; }
标签:des style io os ar for div sp on
原文地址:http://blog.csdn.net/u011345136/article/details/39294867