HDU1686 Oulipo 题解 KMP算法

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1686
题目大意:给你一个子串t和一个母串s,求s中有多少个子串t。
题目分析:KMP模板题。

  • cal_next() :计算字符串t的nxt函数;
  • find_s_has_t_count() :计算s中包含多少个t。

实现代码如下:

#include <cstdio>
#include <string>
using namespace std;
const int maxn = 1001000;

int T, n, m, nxt[maxn], ans;
string s, t; // s代表母串,t代表子串
char ch[maxn];

string read() {
    scanf("%s", ch);
    string tmp_s = ch;
    return tmp_s;
}

void cal_next() {
    m = t.length();
    for (int i = 0, j = -1; i < m; i ++) {
        while (j != -1 && t[j+1] != t[i]) j = nxt[j];
        nxt[i] = (j+1 < i && t[j+1] == t[i]) ? ++j : -1;
    }
}

void find_s_has_t_count() {
    ans = 0, n = s.length(), cal_next();
    for (int i = 0, j = -1; i < n; i ++) {
        while (j != -1 && t[j+1] != s[i]) j = nxt[j];
        if (t[j+1] == s[i]) {
            j ++;
            if (j >= m-1) {
                ans ++;
                j = nxt[j];
            }
        }
    }
    printf("%d
", ans);
}

int main() {
    scanf("%d", &T);
    while (T --) {
        t = read();
        s = read();
        find_s_has_t_count();
    }
    return 0;
}
原文地址:https://www.cnblogs.com/codedecision/p/11794371.html