[HDU3336]Count the string(KMP+DP)
Solution
对KMP的灵活应用
设dp[i]表示前[1,i]的答案
那么dp[i]=dp[p[i]]+1,p[i]为失配函数
Code
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int mo=10007; int n,T,dp[200010],p[200010],Ans; char s[200010]; int main(){ scanf("%d",&T); while(T--){ scanf("%d\n%s",&n,s+1);Ans=0; memset(p,0,sizeof(p)); memset(dp,0,sizeof(dp)); for(int i=2,j=0;i<=n;++i){ while(j>0&&s[i]!=s[j+1]) j=p[j]; if(s[i]==s[j+1]) ++j; p[i]=j; } for(int i=1;i<=n;++i) Ans=(Ans+(dp[i]=dp[p[i]]+1))%mo; printf("%d\n",Ans); } return 0; }