codeforces432D[kmp的next数组的运用]

在这里插入图片描述


解题思路:1.就是nxt数组不断嵌套递归下去就好了


codeforces432D[kmp的next数组的运用]_第1张图片


2.如何统计子串出现的个数
我们从后往前遍历:根据那个图大的子串会包含小的子串,所以我们就处理前缀和将大的个数加到小的里面去


#include 
#include 
 
const int N = 1e5+5;
 
int n, jump[N], c, r[N], dp[N];
char str[N];
 
void getJump() {
    int k = 0;
    n = strlen(str+1);
    for (int i = 2; i <= n; i++) {
        while (k && str[i] != str[k+1])
            k = jump[k];
 
        if (str[i] == str[k+1])
            k++;
        jump[i] = k;
    }
}
 
int main () {
    scanf("%s", str+1);
    getJump();
 
    c = 0;
    for (int i = jump[n]; i; i = jump[i]) {
        r[c] = i;
        c++;
    }
 
    memset(dp, 0, sizeof(dp));
    for (int i = n; i; i--) {
        dp[i]++;
        dp[jump[i]] += dp[i];
    }
 
    printf("%d\n", c+1);
    for (int i = c-1; i >= 0; i--)
        printf("%d %d\n", r[i], dp[r[i]]);
    printf("%d %d\n", n, dp[n]);
    return 0;
}

你可能感兴趣的:(字符串算法)