HDUOJ------1711Number Sequence

时间:2021-12-12 07:29:01

Number Sequence

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

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
kmp 基础
代码:
 /*@kmp扩展@龚细军*/
#include<stdio.h>
#include<string.h>
int aa[],bb[];
int next[];
//依旧使用next数组
void get_next(int *pt,int len)
{
memset(next,,sizeof(next));
int i=,j=-;
next[]=-;
while(i<len)
{
if(j==-||pt[i]==pt[j])
{
++i;
++j;
if(pt[i]!=pt[j])
next[i]=j;
else
next[i]=next[j];
}
else
j=next[j];
}
}
//kmp的扩展
int exd_kmp(int *ps,int *pt,int lens,int lent)
{
int i=-,j=-;
get_next(pt,lent);
while(i<lens)
{
if(j==-||ps[i]==pt[j])
{
++i;
++j;
}
else
j=next[j];
if(j==lent)break;
}
if(j==lent)
return i-j+;
else
return -;
} int main()
{
int test,n,m,i;
scanf("%d",&test);
while(test--)
{
scanf("%d%d",&n,&m);
for(i=;i<n;i++)
scanf("%d",&aa[i]);
for(i=;i<m;i++)
scanf("%d",&bb[i]);
printf("%d\n",exd_kmp(aa,bb,n,m));
}
return ;
}

java代码:

 import java.util.Scanner;

 public class Main {

     public static void main(String args [])
{
mt aa = new mt();
Scanner reader =new Scanner(System.in);
int test=reader.nextInt();
while((test--)>0)
{
aa.lena=reader.nextInt();
aa.lenb=reader.nextInt();
aa.init(aa.lena+1, aa.lenb+1);
for(int i=0;i<aa.lena;i++)
aa.a[i]=reader.nextInt();
for(int i=0;i<aa.lenb;i++)
aa.b[i]=reader.nextInt();
kmp(aa);
}
}
private static void kmp(mt aa)
{
int i,j;
aa.next[i=0]=-1;
j=-1;
while(i<aa.lenb)
{
if(j==-1||aa.b[i]==aa.b[j])
{
i++;
j++;
if(aa.b[i]==aa.b[j])
aa.next[i]=aa.next[j];
else
aa.next[i]=j;
}
else
j=aa.next[j];
}
i=j=0;
while(i<aa.lena&&j<aa.lenb)
{
if(j==-1||aa.a[i]==aa.b[j])
{
i++;
j++;
}
else j=aa.next[j];
}
if(j==aa.lenb)
out(i-aa.lenb+1);
else
out(-1);
}
private static void out(int aa)
{
System.out.println(aa);
}
}
class mt
{
int [] b,a,next;
int lena,lenb;
void init(int lena,int lenb)
{
a=new int [lena];
b=new int [lenb];
next =new int [lenb];
}
}