Oulipo HDU 1686 KMP模板

题目大意:求模式串在主串中的出现次数.

题目思路:KMP模板题

#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<math.h>
#include<map>
#define INF 0x3f3f3f3f
#define MAX 1000005
#define Temp 1000000000
#define MOD 1000000007

using namespace std;

char str1[MAX],str2[MAX];
int n,m,Next[MAX];

void getNext()
{
    int k=-1,i=0;
    Next[0]=-1;
    while(i<m)
    {
        if(k==-1 || str1[i]==str2[k])
            Next[++i]=++k;
        else
            k=Next[k];
    }
}

int Kmp_const()
{
    getNext();
    int i=0,j=0,ans=0;
    while(i<n && j<m)
    {
        if(j==-1 || str1[i]==str2[j])
        {
            i++;
            j++;
        }
        else
            j=Next[j];
        if(j==m)
        {
            ans++;
            j=Next[j];
        }
    }
    return ans;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",str2);
        scanf("%s",str1);
        n=strlen(str1);
        m=strlen(str2);
        int ans=Kmp_const();
        printf("%d
",ans);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/alan-W/p/5966647.html