Oulipo HDU - 1686 (kmp初见讨伐!)

题目链接
题意:给你两个字符串s,t。让你求在s中t出现了多少次。
解题思路:
先写前缀函数(前缀函数的写法点这里了解
然后就是常规KMP模板了。统计答案时重置pos_t的位置。
错误原因:对重置pos_t的操作不是很熟练,导致出了bug。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
//#pragma GCC optimize(3,"Ofast","inline")
#define LL long long
#define MT(a,b) memset(a,b,sizeof(a))
const int mod=1000007;
const int maxn=1e6+5;
const int ONF=-0x3f3f3f3f;
const int INF=0x3f3f3f3f;
char s[maxn],t[maxn];
int pi[maxn];
void get_pi(char *str){
    int len=strlen(str);
    pi[0]=0;
    for (int i=1;i<len;i++){
        int j=pi[i-1];
        while (j>0&&str[i]!=str[j]) j=pi[j-1];
        if (str[i]==str[j]) j++;
        pi[i]=j;
    }
}
int kmp(){
    int len_t=strlen(t),len_s=strlen(s);
    int pos_t=0,pos_s=0,ans=0;
    if (len_t==1&&len_s==1){
        if (s[0]==t[0]) return 1;
        else return 0;
    }
    get_pi(t);
    for (;pos_s<len_s;pos_s++){
        while (pos_t>0&&s[pos_s]!=t[pos_t]){
            pos_t=pi[pos_t-1];
        }
        if (s[pos_s]==t[pos_t]){
            pos_t++;
        }
        if (pos_t==len_t) {
            ans++;
            pos_t=pi[pos_t-1];
        }
    }
    return ans;
}
int main (){
    int T;
    scanf("%d",&T);
    while (T--){
        scanf("%s%s",t,s);
        printf("%d\n",kmp());
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值