KMP常用算法模板

1.求主串中模式串出现了几次

例题 HDU1686

 

#include<cstdio>
#include<cstring>
using namespace std;

#define EPS 1e-7
#define clr(x) memset(x, 0, sizeof(x))
#define long long ll
#define double db
#define PI acos(-1.0)

const int INF = 0x3f3f3f3f;
const int MOD=1000000007;
const int MAXN = 10000000;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
int next[MAXN];
char str1[MAXN];
char str2[MAXN];
int ans;
void getnext(char x[], int m)
{
    int i = 0, j = next[0] = -1;
    while(i < m)
    {
        while(j != -1 && x[j] != x[i])
            j = next[j];
        next[++i] = ++j;
    }
}
void kmp(char x[], char y[], int n, int m)
{
    int i = 0, j = 0;
    while(i < n)
    {
        while(j != -1 && x[j] != y[i])
            j = next[j];
            i++; j++;
            if(j == m)
            {
                ans++;
                j = next[j];
            }
    }
}
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        ans = 0;
        clr(str1);
        clr(str2);
        scanf("%s %s", str1, str2);
        int m = strlen(str1);
        int n = strlen(str2);
        getnext(str1, m);
        kmp(str1, str2, n, m);
        printf("%d\n", ans);
    }
    return 0;
}

 

 

 

2.求主串中模式串出现的位置

HDU1711

 

#include<cstdio>
#include<cstring>
using namespace std;

#define EPS 1e-7
#define clr(x) memset(x, 0, sizeof(x))
#define long long ll
#define double db
#define PI acos(-1.0)

const int INF = 0x3f3f3f3f;
const int MOD=1000000007;
const int MAXN = 1000000 + 5;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
int next[MAXN];
int str1[MAXN];
int str2[MAXN];
int ans;
void getnext(int x[], int m)
{
    int i = 0, j = next[0] = -1;
    while(i < m)
    {
        while(j != -1 && x[j] != x[i])
            j = next[j];
        next[++i] = ++j;
    }
}
void kmp(int x[], int y[], int n, int m)
{
    int i = 0, j = 0;
    while(i < n)
    {
        while(j != -1 && x[j] != y[i])
            j = next[j];
            i++; j++;
            if(j == m)
            {
               ans = i - m + 1;
               return ;
            }
    }
}
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        ans = -1;
        clr(str1);
        clr(str2);
        int n, m;
        scanf("%d %d", &n, &m);
        for(int i = 0; i < n; i++)
            scanf("%d", &str2[i]);
        for(int j = 0; j < m; j++)
            scanf("%d", &str1[j]);
        getnext(str1, m);
        kmp(str1, str2, n, m);
        printf("%d\n", ans);
    }
    return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值