HDU-3336-Count the string (extended the KMP)

link:

https://vjudge.net/problem/HDU-3336

Meaning of the questions:

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.

Ideas:

S prefix number of calculations occur, consider expanding array of KMP Nex, beginning from a starting position matching length i from S0.
I.e., the prefix length of these have appeared. Accumulated and can.

Code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
//#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
#include <string>
#include <assert.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#define MINF 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int MAXN = 2e5+10;
const int MOD = 1e4+7;

char s1[MAXN], s2[MAXN];
int Next[MAXN], Exten[MAXN];

void GetNext(char *s)
{
    int len = strlen(s);
    int a = 0, p = 0;
    Next[0] = len;
    for (int i = 1;i < len;i++)
    {
        if (i >= p || i+Next[i-a] >= p)
        {
            if (i >= p)
                p = i;
            while (p < len && s[p] == s[p-i])
                p++;
            Next[i] = p-i;
            a = i;
        }
        else
            Next[i] = Next[i-a];
    }
}

void ExKmp(char *s, char *t)
{
    int len = strlen(s);
    int a = 0, p = 0;
    GetNext(t);
    for (int i = 0;i < len;i++)
    {
        if (i >= p || i + Next[i-a] >= p)
        {
            if (i >= p)
                p = i;
            while (p < len && s[p] == t[p-i])
                p++;
            Exten[i] = p-i;
            a = i;
        }
        else
            Exten[i] = Next[i-a];
    }

}

int main()
{
    int t, n;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d", &n);
        scanf("%s", s1);
        GetNext(s1);
        int res = 0;
        for (int i = 0;i < strlen(s1);i++)
            res = (res+Next[i])%MOD;
        printf("%d\n", res);
    }

    return 0;
}

Guess you like

Origin www.cnblogs.com/YDDDD/p/11593766.html