zoukankan      html  css  js  c++  java
  • KMP模板

    【代码】

    KMP模板

    #include<algorithm>
    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<cmath>
    #include<queue>
    #include<set>
    using namespace std;
    #define f(i,n) for(int i=1;i<=(n);i++)
    #define ll long long
    #define INF 1<<30
    #define N 100010
    int read()
    {
     	int x=0,f=1;char c=getchar();
     	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
     	while( isdigit(c)){x=x*10+c-'0';c=getchar();}
     	return x*f;
    }
    int n,m;
    char a[N],b[N];
    int next[N];
    void get_next()
    {
        int j=0,k=-1,l=strlen(a);
        next[0]=-1;
        while(j<l)
        {
            if(k==-1||a[j]==a[k])
            {
                k++;
                j++;
                if(a[j]!=a[k])next[j]=k;
                else next[j]=next[k];
            }
            else k=next[k];
        }
        /*for(int i=0;i<j;i++)cout<<next[i]<<" ";
        cout<<endl;*/
    }
    int KMP()
    {
        if(a[0]==''||b[0]=='')return -1;
        get_next();
        int ans=0,i=0,j=0;
        while(b[i]!=''&&a[j]!='')
        {
            if(b[i]==a[j])
            {
                i++;
                j++;
            }
            else
            {
                ans+=j-next[j];
                if(next[j]!=-1)j=next[j];
                else 
                {
                    j=0;
                    i++;
                }
            }
        }
        if(a[j]=='')return ans;
        return -1;
    }
    int main()
    {
        scanf("%s",b);
        scanf("%s",a);
        printf("%d",KMP());
    }
    
  • 相关阅读:
    站立会议第1天
    博客园用户体验
    风险评估
    寻找正整数中1的个数
    每个小组对本组的意见
    对每个小组的评论和建议
    每日scrum(六)
    每日scrum(五)
    分析电脑控制的丹佛机场行李系统
    每日scrum(四)
  • 原文地址:https://www.cnblogs.com/qwerfcxs/p/7807708.html
Copyright © 2011-2022 走看看