hdu 3336 Count the string -KMP&dp

  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

1
4
abab

Sample Output

6

  可以确定肯定不能拿每个前缀跑去KMP,那么来回想一下fail(next)数组的意义——最长相同的前缀和后缀。对于长度为i的前缀,那么f[i]中包含两个长度为f[i]的前缀(大概就这个意思),用cnt[i]表示1-i这一段中有多少个子串与长度为f[i],f[f[i]]的前缀相同(除去cnt[f[i]]这一部分),于是可以得出

  cnt[i] = cnt[f[i]] + 1

  最后把所有cnt求个和就是最终答案

Code

 /**
* hdu
* Problem#3336
* Accepted
* Time:46ms
* Memory:3316k
*/
#include<iostream>
#include<cstdio>
#include<cctype>
#include<cstring>
#include<cstdlib>
#include<fstream>
#include<sstream>
#include<algorithm>
#include<map>
#include<ctime>
#include<set>
#include<queue>
#include<vector>
#include<stack>
using namespace std;
typedef bool boolean;
#define INF 0xfffffff
#define smin(a, b) a = min(a, b)
#define smax(a, b) a = max(a, b)
#ifndef WIN32
#define AUTO "%lld"
#else
#define AUTO "%I64d"
#endif
template<typename T>
inline void readInteger(T& u){
char x;
int aFlag = ;
while(!isdigit((x = getchar())) && x != '-');
if(x == '-'){
x = getchar();
aFlag = -;
}
for(u = x - ''; isdigit((x = getchar())); u = (u << ) + (u << ) + x - '');
ungetc(x, stdin);
u *= aFlag;
} int kase;
int n;
char s[];
int f[];
int cnt[]; inline void init() {
readInteger(n);
gets(s);
gets(s);
} inline void solve() {
f[] = f[] = ;
int j;
for(int i = ; i < n; i++) {
j = f[i];
while(j > && s[i] != s[j]) j = f[j];
f[i + ] = (s[i] == s[j]) ? (j + ) : ();
}
int res = ;
for(int i = ; i <= n; i++)
(cnt[i] = cnt[f[i]] + ) %= , (res += cnt[i]) %= ;
printf("%d\n", res);
} int main() {
readInteger(kase);
while(kase--) {
init();
solve();
}
return ;
}
上一篇:那些优秀的.NET开发者----汪宇杰:从重视细节,到成就技术专家


下一篇:iOS 10 开发适配系列 之 权限Crash问题