http://acm.hdu.edu.cn/showproblem.php?pid=3336
求字符串的前缀在字符串中一共出现多少次。
这个讲解的很清楚,传送门:http://972169909-qq-com.iteye.com/blog/1114968
我用的思想是递推,把next数组向右平移一位,转移方程d[i]=dp[next[i]]+1;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <algorithm> #include <cstring> #include <queue> using namespace std ; int n; char a[200010]; int _next[200010],dp[200010]; void Init_() { int i,k; i = 0; k = -1; _next[0] = -1; while(i < n){ if(k == -1 || a[i] == a[k]){ i++;k++; _next[i] = k; } else k = _next[k]; } } int main() { int t; scanf("%d",&t); while(t--) { scanf("%d%*c",&n); scanf("%s",a); Init_(); int sum=0; memset(dp,0,sizeof(dp)); for(int i=1;i<=n;i++) { dp[i]=dp[_next[i]]+1; sum=(sum+dp[i])%10007; } printf("%d\n",sum); } return 0; }