HDU 1711 Number Sequence(KMP)

来源:互联网 发布:log4j.xml 输出sql 编辑:程序博客网 时间:2024/06/07 02:12

原题链接: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[N], 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[N]. 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 0x3f3f3f3ftemplate<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;}  
0 0
原创粉丝点击