1. 程式人生 > >hdu 3336 Count the string (KMP+DP)

hdu 3336 Count the string (KMP+DP)

scan har include printf esp ui s %u color 次數

題目大意:給你一個字符串,求所有前綴在原串的出現次數之和

打個表推推,KMP+DP隨便水水就過了吧

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <cstring>
 4 #define N 200100
 5 #define mod 10007
 6 #define ui unsigned int
 7 using namespace std;
 8 
 9 int T,n,m,len;
10 int nxt[N];
11 ui f[N];
12 char s[N];
13 void clr()
14 {
15 memset(f,0,sizeof(f)); 16 memset(s,0,sizeof(s)); 17 memset(nxt,0,sizeof(nxt)); 18 } 19 void get_kmp() 20 { 21 int i=0,j=-1; 22 nxt[0]=-1; 23 while(i<=len) 24 { 25 if(j==-1||s[i]==s[j]) 26 { 27 i++; 28 j++; 29 nxt[i]=j; 30
}else{ 31 j=nxt[j]; 32 } 33 } 34 } 35 ui solve() 36 { 37 ui ans=0; 38 for(int i=1;i<=len;i++) 39 { 40 if(nxt[i]>=0) f[i]=f[nxt[i]]+1; 41 else f[i]=1; 42 f[i]%=mod; 43 ans+=f[i]; 44 ans%=mod; 45 } 46 return
ans; 47 } 48 49 int main() 50 { 51 scanf("%d",&T); 52 while(T--) 53 { 54 scanf("%d",&n); 55 clr(); 56 scanf("%s",s); 57 len=strlen(s); 58 get_kmp(); 59 printf("%u\n",solve()); 60 } 61 return 0; 62 } 63 64 65

hdu 3336 Count the string (KMP+DP)