【KMP+DP】HDU - 3336 - Count the string
阿新 • • 發佈:2018-11-10
題目連結<http://acm.hdu.edu.cn/showproblem.php?pid=3336>
題意:
給出一個字串,求出所有前綴出現次數的和。
題解:
設方程表示內字尾能匹配到的字首個數,
因為KMP匹配到的是相同的最大字尾與最大字首,所以可以進行轉移:
加上的1代表本身作為一個字尾和字首匹配。
#include<iostream> #include<cstdio> #include<algorithm> #include<string.h> #include<string> using namespace std; typedef long long ll; const int N=1e6+7; const int mod=10007; char s[N]; int nex[N],dp[N],n; int getnex(){ int i=0,j=-1; nex[i]=-1; while(i<n){ if(j==-1||s[i]==s[j]) i++,j++,nex[i]=j; else j=nex[j]; } } int main(){ int t; scanf("%d",&t); while(t--){ scanf("%d%s",&n,s); getnex(); int ans=0; for(int i=1;i<=n;i++){ dp[i]=dp[nex[i]]+1; ans=(ans+dp[i])%mod; } printf("%d\n",ans); } }