[SDUT](3311)数据结构实验之串三:KMP应用 ---KMP(串)

数据结构实验之串三:KMP应用

Time Limit: 1000MS  Memory Limit: 65536KB
Problem Description

有n个小朋友,每个小朋友手里有一些糖块,现在这些小朋友排成一排,编号是由1到n。现在给出m个数,能不能唯一的确定一对值l和r(l <= r),使得这m个数刚好是第l个小朋友到第r个小朋友手里的糖块数?

Input

首先输入一个整数n,代表有n个小朋友。下一行输入n个数,分别代表每个小朋友手里糖的数量。

之后再输入一个整数m,代表下面有m个数。下一行输入这m个数。

Output

 如果能唯一的确定一对l,r的值,那么输出这两个值,否则输出-1

Example Input
5
1 2 3 4 5
3
2 3 4
Example Output
2 4

解题新知:注意唯一确定的一个模式串!

AC代码:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int next[1000005];
int t[1000005];
int p[1000005];
int m,n;
void setNext()
{
    int j=0;
    int t=next[0]=-1;
    while(j<n)
    {
        if(t<0||p[j]==p[t])
        {
            j++;
            t++;
            next[j]=t;
        }
        else
            t=next[t];
    }
}
void kmp()
{
    int i=0;
    int j=0;
    int flag=0;
    int l,r;
    memset(next,0,sizeof(next));
    setNext();
    while(i<m)
    {
        if(j<0||t[i]==p[j])
        {
            i++;
            j++;
        }
        else
            j=next[j];
        if(j==n)
        {
            flag++;
            if(flag>=2)
            {
                cout<<-1<<endl;
                return;
            }
            l=i-n+1;
            r=i;
        }
    }
    if(flag==1)
        printf("%d %d\n",l,r);
    else
        printf("-1\n");
}
int main()
{
    scanf("%d",&m);
    for(int i=0;i<m;i++)
        cin>>t[i];
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        cin>>p[i];
    setNext();
    kmp();
    return 0;
}


转载于:https://www.cnblogs.com/WangMeow/p/7535950.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值