HDU 3336 Count the string(KMP 理解)

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

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


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
 


Authorforeverlin@HNU 


SourceHDOJ Monthly Contest – 2010.03.06 


Recommendlcy 這個題目好像有點歧義,不過不要想太多,直接在next值上作文章就OK 了這個next值記錄的就是當前位置向前 多少個和這個字串開頭多少個相等有了這樣我們只要記錄每個next值對應有多少個,然後加上n個自身的一個匹配就OK 了!這個題目的關鍵還是對KMP的理解,本質上kmp的next就是表示串內關係的一個值,理解KMP是理解AC自動機的基礎

#include <iostream>#include <string.h>#include <stdio.h>using namespace std;char str[200001];int next[200001];int rec[200001];int n;int get_next(){int i=0,j=-1;next[0]=-1;while(str[i]){if(j==-1 || str[i]==str[j]){i++;j++;next[i]=j;}elsej=next[j];}return 0;}int main(){int t,i,j;int ans;scanf("%d",&t);while(t--){ans=0;scanf("%d",&n);scanf("%s",str);memset(rec,0,sizeof(rec));str[n]='a';str[n+1]=0;get_next();for(i=1;i<=n;i++)rec[next[i]]++;for(i=1;i<=n;i++)if(rec[i] > 0){ans+=rec[i];ans%=10007;}ans+=n;printf("%d\n",ans%10007);}return 0;}

聯繫我們

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