欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Count the string

程序员文章站 2022-05-02 17:38:28
...

题目:

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


分析:

这道题是要求我们求出有每个前缀在这个字符串中出现的次数。
首先每个开头作为首字母的子串都是一个前缀,除此之外求出他们在后面出现的次数即可。那么这个总数就分为两部分:一部分值是这个字符串的长度,因为开头首字符的子串和字符串长度相等;另一部分值可以用一个for循环从头跑到尾每次遇到Next[i]的值不为0时,就说明出现了一次循环,总个数加一,并且一直向前回溯,每回溯一次就说明这个长度的字符串又多出现了一次依旧总个数加一,跑完整个字符串,就求出了以开头首字符的不同字符串在后面出现的次数。


代码:

#include <cstdio>
#include <iostream>
#include <string>
using namespace std;

int Next[10000005];
string str;

void get_next(){
    int len = str.size();
    int j = 0, k = -1;
    Next[0] = -1;
    while(j < len){
        if(k == -1 || str[j] == str[k]){
            k++;
            j++;
            Next[j] = k;
        }
        else
            k = Next[k];
    }
}

int main(){
    int t, n;
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        cin >> str;
        get_next();
        int sum = n;
        for(int i = 1; i <= str.size(); i++){
            int j = i;
            while(Next[j] != 0){
                sum++;
                j = Next[j];
                sum %= 10007;
            }
        }
        cout << sum%10007 << endl;
    }
    return 0;
}