hdu3336 Count the string(kmp+dp)_動態歸劃

來源:互聯網
上載者:User

題意:給出一個字串,求所有首碼串出現的總次數。


abab 的首碼串有:a  ab  aba  abab

其中a出現2次

總共出現6次。


思路:先是用KMP求出第i個字元重複的最長首碼的結束位置

           dp[i]代表長為i的首碼串(數量1)與其有重複首碼數量。


#include<iostream>#include<queue>using namespace std;const int N = 222222,M = 10007;int dp[N],next[N];char s[N];void get_next(int n){for (int i=2,j=0;i<=n;i++){//cout<<s[j+1]<<s[i]<<endl;while (j && s[j+1]!=s[i]) j=next[j];if (s[j+1] == s[i]) j++;next[i]=j;}}int main(){freopen("in","r",stdin);int t,n;cin>>t;while (t--){scanf("%d",&n);scanf("%s",s+1);s[0]='#';get_next(n);for (int i=1;i<=n;i++) dp[i]=1;int ans=0;//for (int i=1;i<=n;i++) cout<<next[i]<<' ';cout<<endl;for (int  i=1;i<=n;i++){dp[i]=dp[next[i]]+1;ans+=dp[i];ans%=M;}printf("%d\n",ans);}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.