KMP-Count the string-HDU - 3336

KMP-Count the string-HDU - 3336

題目:

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

題意:

nn給定長度爲n的字符串,求其n個前綴在整個字符串中出現的次數的總和。

:abab:a,2:ab,2:aba1:abab1=2+2+1+1=6樣例:abab\\前綴:a,出現2次。\\前綴:ab,出現2次。\\前綴:aba,出現1次。\\前綴:abab,出現1次。\\總和=2+2+1+1=6。

題解:

NextiNext[i]iicnt[i]=cnt[Next[i]]+1考察對Next數組的理解。\\前i個字符的前綴必然包含了前Next[i]個字符的前綴,\\那麼前i個字符中前綴的個數等於其前綴子串中前綴的個數加上前i個字符中的一個後綴,\\即cnt[i]=cnt[Next[i]]+1。

:ababi=5abcababab,cnt[5]=cnt[2]+1ababcabdp如:abab,i=5時,abcab中前前綴的個數可以由前綴ab中的前綴的個數再加上一個後綴ab,即cnt[5]=cnt[2]+1。\\以爲前綴ab是包含在abcab當中的,是一個dp的過程。


代碼:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#define ull unsigned long long
#define inf 0x7fffffff
using namespace std;
const int N=2e5+10;
const int mod=1e4+7;
int T,n;
char s[N];
int cnt[N],Next[N];

void get_next()
{
    for(int i=2,j=0;i<=n;i++)
    {
        while(j&&s[i]!=s[j+1]) j=Next[j];
        if(s[i]==s[j+1]) j++;
        Next[i]=j;
    }
}

int main()
{
    cin>>T;
    while(T--)
    {
        scanf("%d%s",&n,s+1);

        get_next();

        int ans=0;
        for(int i=1;i<=n;i++)
        {
            cnt[i]=(cnt[Next[i]]+1)%mod;
            ans=(ans+cnt[i])%mod;
        }

        printf("%d\n",ans);
    }

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章