题目链接:hdu3336
假设两串字符完全相等,next[j]=i,代表s[1...i]==sum[j-i+1....j],这一段其实就是前缀
i~j之间已经不可能有以j结尾的子串是前缀了,不然next【j】就不是 i 了
设dp【i】:以string[i]结尾的子串总共含前缀的数量
所以dp[j]=dp[i]+1,即以i结尾的子串中含前缀的数量加上前j个字符这一前缀
#include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <iostream> using namespace std; const int N = 200005; char a[N]; int next[N],d[N]; void get_next(char *b) { int i = -1, j = 0; next[0] = -1; int len = strlen(b); while(j < len) { if(i == -1 || b[i] == b[j]) next[++j] = ++i; else i = next[i]; } } int main() { int T,i,n; scanf("%d",&T); while(T--) { scanf("%d%s",&n,a); get_next(a); for(i = 1; i <= n; i ++) d[i] = 1; d[0] = 0; int sum = 0; for(i = 1; i <= n; i ++) { d[i] = d[next[i]] + 1; sum += d[i]%10007; } printf("%d\n",sum%10007); } return 0; }
hdu3336(KMP+DP),布布扣,bubuko.com
原文:http://blog.csdn.net/jzmzy/article/details/20143803