POJ 3461 Oulipo

来源:互联网 发布:php 开发教育网站框架 编辑:程序博客网 时间:2024/05/21 08:53

思考:kmp的灵活运用,模式字符串当匹配成功时候,文本字符串的下一位和模式字符串的第 f[lenw] 开始匹配,详细见代码。

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxw = 10010;const int maxt = 1000010;char w[maxw+5];char t[maxt+5];int f[maxw+5];//Accepted1716K94MSG++973B2014-04-05 20:20:23void getFail() {    int len = strlen(w);    f[0] = 0, f[1] = 0;    int j = 0;    for(int i = 1; i < len; i++) {        j = f[i];        while(j && w[j]!=w[i]) j = f[j];        f[i+1] = w[j]==w[i] ? j+1 : 0;    }}int match() {    getFail();    int cnt = 0;    int lenw = strlen(w), lent = strlen(t);    int j = 0;    for(int i = 0; i < lent; i++) {        while(j && w[j]!=t[i]) j = f[j];        if(w[j]==t[i]) j++;        if(j==lenw) {            cnt++;            j = f[lenw];       // !!! key point.        }    }    return cnt;}int main(){    int T;    scanf("%d", &T);    getchar();    while(T--) {        gets(w);        gets(t);        int res = match();        printf("%d\n", res);    }    return 0;}

0 0