HDU 1711 Number Sequence(简单KMP)

来源:互联网 发布:什么是软件外包公司 编辑:程序博客网 时间:2024/04/30 14:45

Number Sequence

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8237    Accepted Submission(s): 3752


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
213 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 1 313 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 2 1
 

Sample Output
6-1
 

                  题目地址:Number Sequence

AC代码:
#include<iostream>#include<cstdio>#include<cstring>#include<string>using namespace std;int len1,len2,a[1000005],b[10005],next[10005];void getnext(){     int i,j;     next[0]=0,next[1]=0;     for(i=1;i<len2;i++)     {          j=next[i];          while(j&&b[i]!=b[j])               j=next[j];          if(b[i]==b[j])               next[i+1]=j+1;           else               next[i+1]=0;     }}void KMP(){     int i,j=0;     int flag=0;     for(i=0;i<len1;i++)     {          while(j&&a[i]!=b[j])               j=next[j];          if(a[i]==b[j])               j++;          if(j==len2)          {               flag=1;               printf("%d\n",i-len2+2); //需要转换输出尾标               break;          }     }     if(!flag)          puts("-1");}int main(){     int T,i;     cin>>T;     while(T--)     {          scanf("%d%d",&len1,&len2);          for(i=0;i<len1;i++)               scanf("%d",&a[i]);          for(i=0;i<len2;i++)               scanf("%d",&b[i]);          getnext();          KMP();     }     return 0;}