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

HDU 1711 Number Sequence(KMP)

2016-10-21 22:50 295 查看
原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711

Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)

Problem 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.

Input

The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], …… , a
. The third line contains M integers which indicate b[1], b[2], …… , b[M]. All integers are in the range of [-1000000, 1000000].

Output

For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.

Sample Input

2

13 5

1 2 1 2 3 1 2 3 1 3 2 1 2

1 2 3 1 3

13 5

1 2 1 2 3 1 2 3 1 3 2 1 2

1 2 3 2 1

Sample Output

6

-1

Source

HDU 2007-Spring Programming Contest

题解:本题属于KMP模板题,模板来自LRJ紫书。(后附KMP模板)

AC代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<string>
#include<queue>
#include<sstream>
#include<list>
#include<stack>
#define ll long long
#define ull unsigned long long
#define rep(i,a,b) for (int i=(a),_ed=(b);i<=_ed;i++)
#define rrep(i,a,b) for(int i=(a),_ed=(b);i>=_ed;i--)
#define fil(a,b) memset((a),(b),sizeof(a))
#define cl(a) fil(a,0)
#define PI 3.1415927
#define inf 0x3f3f3f3f
template<typename N>N gcd(N a, N b) { return b ? gcd(b, a%b) : a; }
using namespace std;
int a[1000005];
int b[10005];
int nexta[10005];
int T,n,m;
void ininext()
{
nexta[0]=nexta[1]=0;
for(int i=1;i<m;++i)
{
int j=nexta[i];
while(j&&b[i]!=b[j]) j=nexta[j];
nexta[i+1]=b[i]==b[j]?j+1:0;
}
}
void kmp()
{

ininext();
int j=0;
rep(i,0,n-1)
{
while(j&&b[j]!=a[i]) j=nexta[j];
if(b[j]==a[i]) j++;
if(j==m) {cout<<i-m+2<<endl;return;}
}
cout<<-1<<endl;
return;
}
int main(void)
{
cin>>T;
while(T--)
{
cl(nexta);
scanf("%d%d",&n,&m);
rep(i,0,n-1) scanf("%d",&a[i]);
rep(i,0,m-1) scanf("%d",&b[i]);
kmp();
}
return 0;
}


KMP模板

void ininext()
{
nexta[0]=nexta[1]=0;
for(int i=1;i<m;++i)
{
int j=nexta[i];
while(j&&b[i]!=b[j]) j=nexta[j];
nexta[i+1]=b[i]==b[j]?j+1:0;
}
}
void kmp()
{

ininext();
int j=0;
rep(i,0,n-1)
{
while(j&&b[j]!=a[i]) j=nexta[j];
if(b[j]==a[i]) j++;
if(j==m) {cout<<i-m+2<<endl;return;}
}
cout<<-1<<endl;
return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  kmp hdu acm