您的位置:首页 > 产品设计 > UI/UE

HDU 1711 Number Sequence

2016-09-04 19:38 274 查看
Description

Given two sequences of numbers : a[1], a[2], …… , a
, and b[1], b[2], …… , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], …… , a[K + M - 1] = b[M]. If there are more than one K exist, output the smallest one.

【题目大意】

给定两个字符串A、B,要求找出B最早在A中出现的位置,输出这个位置,如果无法匹配,就输出-1。

【题目分析】

很显然的一道KMP裸题。

【代码】

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int a[1000001],b[10001];
int ne[10001],f[1000001];
int main()
{
int n,m,tt;
scanf("%d",&tt);
while (tt--)
{
memset(ne,0,sizeof ne);
memset(f,0,sizeof f);
scanf("%d%d",&n,&m);
for (int i=1;i<=n;++i) scanf("%d",&a[i]);
for (int i=1;i<=m;++i) scanf("%d",&b[i]);
for (int i=2,j=0;i<=m;++i)
{
while (j&&b[j+1]!=b[i]) j=ne[j];
if (b[j+1]==b[i]) j++;
ne[i]=j;
}
for (int i=1,j=0;i<=n;++i)
{
while (j&&b[j+1]!=a[i]) j=ne[j];
if (b[j+1]==a[i]) j++;
f[i]=j;
}
int flag=-1;
for (int i=1;i<=n;++i) if (f[i]==m) {flag=i-m+1;break;}
printf("%d\n",flag);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu