hdu 3336
http://acm.hdu.edu.cn/showproblem.php?pid=3336
題意:給一個字符串,問你這個字符串的前綴在這個字符串出現的次數
思路:先對字符串求一次next數組,然后枚舉每一個終點,它的前綴其實對于它的next[len]進行遞歸尋找,知道他的next[len]為0,那么遞歸的次數也就是它的前綴出現的次數
然后這個我們其實可以用dp來做,也就是dp[i] = dp[next[i]] +1?
1 #include <stdio.h> 2 #include <string.h> 3 const int mod = 10007; 4 5 char str[200050]; 6 int n; 7 int num[200050]; 8 int next[200050]; 9 char tmp[200050]; 10 11 12 void getnext() 13 { 14 next[0] = -1; 15 int i = 0,j = -1; 16 while(i<n) 17 { 18 if(j==-1||str[i]==str[j]) 19 next[++i]=++j; 20 else 21 j = next[j]; 22 } 23 } 24 25 int main() 26 { 27 int t; 28 scanf("%d",&t); 29 while(t--) 30 { 31 scanf("%d",&n); 32 scanf("%s",str); 33 memset(num,0,sizeof(num)); 34 memset(next,0,sizeof(next)); 35 getnext(); 36 int ans = 0; 37 for(int i = 1;i<=n;i++) 38 { 39 num[i] = num[next[i]] +1; 40 ans = (ans+num[i])%mod; 41 } 42 printf("%d\n",ans); 43 } 44 return 0; 45 }?
轉載于:https://www.cnblogs.com/Tree-dream/p/7443897.html
總結
- 上一篇: python基础之if、while、fo
- 下一篇: kinect2的标定