KMP hdu1686

hdu1686
详细解释参见博客

//#include <bits/stdc++.h>
#include<stdio.h>
#include<string.h>
#include<string>
#include<math.h>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#include<stack>
#include<map>
#include<set>
#include<stdlib.h>
#include<time.h>
#include <iomanip>
#define lowbit(x) (x&(-x))
#define inf  0x7fffffff
#define linf 0x7fffffffffffffff
#define fil(x,y) memset(x,y,sizeof(x))
#define fup(i,x,y) for(int i=(x);i<=(y);i++)
#define fdn(i,x,y) for(int i=(x);i>=(y);i--)
#define sp(x) setprecision(x)
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d%d",&n,&m)
#define sddd(n,m,k) scanf("%d%d%d",&n,&m,&k)
#define sld(n) scanf("%lld",&n)
#define sldd(n,m) scanf("%lld%lld",&n,&m)
#define slddd(n,m,k) scanf("%lld%lld%lld",&n,&m,&k)
#define sf(n) scanf("%lf",&n)
#define sff(n,m) scanf("%lf%lf",&n,&m)
#define sfff(n,m,k) scanf("%lf%lf%lf",&n,&m,&k)
#define sc(n) scanf("%s",n)
#define pf(x) printf("%d\n",x)
#define pfl(x) printf("%lld\n",x)
#define pff(x) printf("%lf\n",x)
#define debug printf("!!\n");
#define N 4000*102
#define M 4000009
#define pi acos(-1)
#define eps 1e-2
//cout.setf(ios::fixed);
//freopen("out.txt","w",stdout);// freopen("in.txt","r",stdin);
using namespace std;
typedef long long  ll;
typedef double db;
const int mod=1e9+7;
char c[1000005],s[1000005];
int ne[1000005],ans,len1,len2;
void ini()
{
    ne[0]=-1;
    int k=-1;
    fup(i,1,len1-1)
    {
        while(k>-1&&c[k+1]!=c[i]) k=ne[k];
        if(c[k+1]==c[i]) k++;
        ne[i]=k;
    }
}
void kmp()
{
    int k=-1;
    fup(i,0,len2-1)
    {
        while(k>-1&&c[k+1]!=s[i]) k=ne[k];

        if(c[k+1]==s[i]) k++;
        if(k==len1-1)
        {
            ans++;
            k=ne[k];//可有可无
        }

    }
}
void solve()
{
    scanf("%s%s", c, s);
    len1=strlen(c);
    len2=strlen(s);
    ans=0;
    ini();
    kmp();
    pf(ans);
}
int main()
{
    int tt=1,k=1;
    sd(tt);
  //  getchar();
     while(tt--)
    {
        solve();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_25973789/article/details/79979474