HDU 3336 Count the string

Count the string

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Problem Description

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

题意:

比如abab中a,ab,aba,abab在原串中的个数的总和为2+2+1+1 = 6。(举个例子应该更好理解)

思路:

首先就是求出Next数组,这样才知道可以用动态规划,设dp[i]表示子串mo[0~i]共含有以mo[i]为结尾的前缀的数目,则以mo[i]结尾的前缀数就是自己本身加上以mo[Next[i]]结尾的前缀数,然后还要取模。

#include <iostream>
#include <cstdio>
#include <cstring>
const int maxn = 2e+5 + 10;
const int mod = 10007;
char mo[maxn];
int Next[maxn], dp[maxn];
void GetNext() {
    int i = 0, j = -1, len = strlen(mo);
    while (i < len) {
        if (j == -1 || mo[i] == mo[j]) Next[++i] = ++j;
        else j = Next[j];
    }
}
int main() {
    int t, n;
    scanf("%d", &t);
    while (t--) {
        memset(dp, 0, sizeof(dp));
        scanf("%d", &n);
        scanf("%s", mo);
        Next[0] = -1;
        GetNext();
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            dp[i] = dp[Next[i]] + 1;
            sum = (dp[i] + sum) % mod;
        }
        printf("%d\n", sum);
    }
    return 0;
}

全部评论

相关推荐

11-13 14:37
门头沟学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
11-21 11:29
已编辑
斯卡蒂味的鱼汤:知道你不会来数马,就不捞你😂最近数马疯狂扩招,招聘要求挺低的,你能力肯定够,应该就是因为太强了,知道你不会来才不捞你
投递腾讯云智研发等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务