KMP

http://acm.hdu.edu.cn/showproblem.php?pid=1711

#include"stdio.h"  
#include"string.h"  
#include"stdlib.h"  
int n,m;  
int next[10011];  
int a[1000111];  
int b[10011];  
void getnext()  
{  
    int j,k;  
    j=0;  
    k=-1;  
    next[0]=-1;  
    while(j<m)  
    {  
        if(k==-1 || b[j]==b[k]) next[++j]=++k;  
        else                    k=next[k];  
    }  
}  
int KMP()  
{  
    int i,j;  
    j=0;  
    for(i=0;i<n;)  
    {  
        if(a[i]==b[j])  
        {  
            if(j==m-1)  return i-(m-1)+1;  
            i++;j++;  
        }  
        else  
        {  
            j=next[j];  
            if(j==-1)   {i++;j=0;}  
        }  
    }  
    return -1;  
}  
int main()  
{  
    int T;  
    int i;  
    int ans;  
    scanf("%d",&T);  
    while(T--)  
    {  
        scanf("%d%d",&n,&m);  
        for(i=0;i<n;i++) scanf("%d",&a[i]);  
        for(i=0;i<m;i++) scanf("%d",&b[i]);  
  
        if(n<m)  {printf("-1\n");continue;}  
  
        getnext();  
        ans=KMP();  
        printf("%d\n",ans);  
    }  
    return 0;  
}  

#include<bits/stdc++.h>//https://www.bnuoj.com/v3/contest_show.php?cid=6865#problem/C
using namespace std;
const int N=5e6+10;
char a[N],b[N],ans[N];
int next[N],pos[N];
void getnext()
{
    int i=0,j=-1;
    next[0]=-1;
    while(b[i]!='\0')
    {
        if(j==-1||b[i]==b[j]) next[++i]=++j;
        else                  j=next[j];
    }
}
void kmp()
{
    getnext();
    int i=0,j=0,cnt=0,x=strlen(b);
    while(a[i]!='\0')
    {
        ans[cnt]=a[i++];
        while(!(j==-1||ans[cnt]==b[j]))
            j=next[j];
        j++;cnt++;
        pos[cnt]=j;
        if(j==x) cnt-=x,j=pos[cnt];
    }
    ans[cnt]='\0';
}
int main()
{
    int n,m,x,y,t;
    while(~scanf("%s%s",b,a))
    {
        kmp();
        printf("%s\n",ans);
    }
    return 0;
}

#include<bits/stdc++.h>//http://acm.hdu.edu.cn/showproblem.php?pid=1711
using namespace std;
const int N=5e6+10;
char a[N],b[N],ans[N];
int next[N];
void getnext()
{
    int i=0,j=-1;
    next[0]=-1;
    while(b[i]!='\0')
    {
        if(j==-1||b[i]==b[j]) next[++i]=++j;
        else                  j=next[j];
    }
}
int kmp()
{
    getnext();
    int i=0,j=0;
    while(a[i]!='\0')
    {
        if(a[i]==b[j])
        {
            if(b[j+1]=='\0') return i-j+1;
            i++,j++;
        }
        else
        {
            j=next[j];
            if(j==-1) i++,j=0;
        }
    }
    return -1;
}
int main()
{
    int n,m,x,y,t;
    while(~scanf("%s%s",a,b))
    {
        printf("%d\n",kmp());
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值