Count the string[KMP]HDU3336

Exam link http://acm.hdu.edu.cn/showproblem.php?pid=3336 

  This question is to use a simple array of KMP next, next first understand the significance array: prefixes and suffixes match indicates the longest length of the string pattern consisting of i-th character string before the next [i], for example on the string "abcdabe", its next [3] = 0, because the character sub-string consisting of the first three characters "abc" longest match length of the prefix and suffix 0, the next [6] = 2, as for the substring " abcdab ", it can match the largest prefix of suffix" ab ", a length of 2, corresponding to its maximum matching length prefixes and suffixes.

  For this question, we start from a position next to traverse the entire array, each first prefix string has its own contribution to one of the answers are, so first ans ++, in addition, when the next and [I] 0 is a value greater than the position described before the i-th sub-string of characters has a suffix greater than zero prefix match, i.e., the prefix string repeated once this position, so in this case ans plus 1.

 Refer to code:

#include<bits/stdc++.h>

using namespace std;
char s[200010];
int t,n,nex[200010];
int ans;

void getNex(){
    nex[0]=-1;
    int k=-1,j=0;
    while(j<n){
        if(k==-1||s[j]==s[k]){
            ++j;++k;
                nex[j]=k;
        }
        else k=nex[k];
    }
}
int main(){
    scanf("%d",&t);
    while(t--){
        ans=0;
        scanf("%d%s",&n,s);
        getNex();
        for(int i=1;i<=n;i++){
            ans++;
            if(nex[i]!=0)
                ans++;
            ans%=10007;
        }
        printf("%d\n",ans);
    }
    return 0;
}
xxmlala-Code

  

Guess you like

Origin www.cnblogs.com/xxmlala-fff/p/11431921.html