HDU

来源:互联网 发布:淘宝尺寸文字自定义 编辑:程序博客网 时间:2024/05/21 11:11

模板题

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 1000 + 10;char s[maxn], p[maxn];int lens, lenp, Next[maxn];void makeNext() {    int pos = 0, len = 0;    Next[pos] = len;    for (pos = 1; pos < lenp; pos++) {        while (len && p[pos] != p[len]) len = Next[len - 1];        if (p[pos] == p[len]) len++;        Next[pos] = len;    }}int kmp() {    int ans = 0;    makeNext();    for (int i = 0, j = 0; i < lens; i++) {        while (j && s[i] != p[j]) j = Next[j - 1];        if (s[i] == p[j]) j++;        if (j == lenp) {            ans++;            j = 0;        }    }    return ans;}int main() {    while (~scanf("%s", s) && s[0] != '#') {        scanf("%s", p);        lens = strlen(s), lenp = strlen(p);        printf("%d\n", kmp());    }    return 0;}


原创粉丝点击