hdu3336 dp+求next数组
dp[i]=dp[next[i]]+1;//dp[i]表示以i结尾能和前面多少前缀匹配,思考
ans=sum{dp[i]}
1 #include<stdio.h> 2 #include<string.h> 3 #include<algorithm> 4 using namespace std; 5 int m,dp[200005],next[200005]; 6 char s[200005]; 7 void getnext() 8 { 9 int i,j; 10 next[1]=0; j=0; 11 for (i=2;i<=m;i++) 12 { 13 while (j>0&&s[j+1]!=s[i]) j=next[j]; 14 if (s[j+1]==s[i]) j++; 15 next[i]=j; 16 } 17 } 18 int main() 19 { 20 int T,i,sum; 21 scanf("%d",&T); 22 while (T--) 23 { 24 scanf("%d",&m); 25 scanf("%s",s); 26 for (i=m;i>=1;i--) 27 s[i]=s[i-1]; 28 getnext(); 29 dp[0]=sum=0; 30 for (i=1;i<=m;i++){ 31 dp[i]=dp[next[i]]+1; 32 sum=(sum+dp[i])%10007; 33 } 34 printf("%d\n",sum); 35 } 36 return 0; 37 }