HDU 3336 Count the string【KMP】

版权声明:转载什么的好说,附上友链就ojek了,同为咸鱼,一起学习。 https://blog.csdn.net/sodacoco/article/details/88030733

题目:

It 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. 

Input

The 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. 

Output

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

Sample Input

1
4
abab

Sample Output

6

题目大意: 

       求每一个前缀在字符串中出现的次数

解题思路:

       next数组的值就是记录当前位置向前多少个和这个字符串开头多少个相等,有了这样我们只要记录每个next这对应有多少个,然后加上n个自身的一个匹配就行了。

实现代码:

#include<cstdio>
#include<fstream>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstring>
#include<string.h>
#include<queue>
#include<vector>
#include<map>
using namespace std;

int n,Next[200005];
string s;

void getnext(){
    int i,j;
    i=-1;j=0;
    Next[0]=-1;
    while (j<n){
        if(i==-1 || s[i]==s[j]){
            j++; i++;
            Next[j]=i;
        }
        else i=Next[i];
     }
}
int main(){
    ios::sync_with_stdio(false);    //加速
    cin.tie(0);
    int t,j,ans;
    cin>>t;
    while(t--){
        cin>>n;
        cin>>s;
        ans=n;    //一定存在的串个数
        getnext();
        for(int i=1; i<=n; i++){
            for(j=Next[i]; j; ans++)
                j=Next[j];
            ans%=10007;
        }
        cout<<ans%10007<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sodacoco/article/details/88030733
今日推荐