HDU 3336 Count the string(KMP+dp)

來源:互聯網
上載者:User
Count the string

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3132    Accepted Submission(s): 1458


Problem DescriptionIt is well known that AekdyCoin is good at string problems as well as number theory problems. When given a string s, we can write down all the non-empty prefixes of this string. For example:
s: "abab"
The prefixes are: "a", "ab", "aba", "abab"
For each prefix, we can count the times it matches in s. So we can see that prefix "a" matches twice, "ab" matches twice too, "aba" matches once, and "abab" matches once. Now you are asked to calculate the sum of the match times for all the prefixes. For "abab",
it is 2 + 2 + 1 + 1 = 6.
The answer may be very large, so output the answer mod 10007. 


InputThe first line is a single integer T, indicating the number of test cases.
For each case, the first line is an integer n (1 <= n <= 200000), which is the length of string s. A line follows giving the string s. The characters in the strings are all lower-case letters. 


OutputFor each case, output only one number: the sum of the match times for all the prefixes of s mod 10007. 


Sample Input

14abab
 


Sample Output

6
             題目大意:給你一個串,統計這個串所有的首碼在串中出現的次數,然後模上100007.        解題思路:乍一看,還真的不知道如何分析。將問題分解成以a[i]結束的子串包含的首碼,然後dp,即可求出。具體思路見代碼中有詳解。
       題目地址:Count the string
AC代碼:
/*      next[j]=i, dp[j]=dp[i]+1;  以i為最後一個字母首碼有dp[i]個,則以j為最後一個字母首碼有dp[i]+1個,加一個本身.  下面是一個例子:            a b a b c a b a b c d   next[i]  0 0 1 2 0 1 2 3 4 5 0   dp[i]    1 1 2 2 1 2 2 3 3 2 1   設dp[i]:以a[i]結尾的子串總共含首碼的數量*/#include<iostream>#include<cstring>#include<string>#include<cstdio>#define MO 10007using namespace std;int len,next[200005],dp[200005],res;char a[200005];void getnext(){     int i,j;     next[0]=0,next[1]=0;     for(i=1;i<len;i++)     {          j=next[i];          while(j&&a[i]!=a[j])               j=next[j];          if(a[i]==a[j])             next[i+1]=j+1;            else               next[i+1]=0;     }}int main(){     int T,i;     scanf("%d",&T);     while(T--)     {          scanf("%d%s",&len,a);          getnext();          memset(dp,0,sizeof(dp));          res=0;          for(i=1;i<=len;i++)          {               dp[i]=dp[next[i]]+1;               res=(res+dp[i])%MO;          }          cout<<res<<endl;     }     return 0;}/*311ababcababcd*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.