HDU-1686-oulipo

这题就是KMP的模板题,讲解:
https://blog.csdn.net/qq_41090676/article/details/86801491

#include <cstdio>
#include <cstring>
char p[10005], s[1000005];
int next[10005], ans;

void getnext()
{
    next[0] = -1;
    int j = 0, k = -1, len=strlen(p);
    while (j<len) {
        if (k==-1||p[j]==p[k])
            if (p[++j]==p[++k])
                next[j] = next[k];
            else
                next[j] = k;
        else
            k = next[k];
    }
}

void KMP()
{
    ans = 0;
    int len = strlen(p), len1 = strlen(s);
    int i = 0, j = 0;
    while (i<len1) {
        if (j==-1||s[i]==p[j]) {
            i++;
            j++;
        }
        else
            j = next[j];
        if (j==len)
            ans++;
    }
}

int main()
{
    int t;
    scanf("%d", &t);
    while (t--) {
        scanf("%s%s", p, s);
        getnext();
        KMP();
        printf("%d\n", ans);
    }
    return 0;
}
posted @ 2019-02-09 17:18  xyee  阅读(137)  评论(0编辑  收藏  举报