Number Sequence

Number Sequence

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


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
 
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <string>
 7 #include <vector>
 8 #include <stack>
 9 #include <queue>
10 #include <set>
11 #include <map>
12 #include <iomanip>
13 using namespace std;
14 const int INF=0x5fffffff;
15 const int MS=1000005;
16 const double EXP=1e-8;
17 int str1[MS],str2[MS/10];
18 int next[MS/10];
19 int N,M;
20 
21 void get_next(int s[],int next[])
22 {
23     int i,j;
24     i=1;j=0;
25     next[1]=0;
26    // int len=strlen(s);
27     int len=M;
28     while(i<len)
29     {
30        if(j==0||s[i-1]==s[j-1])
31        {
32            i++;
33            j++;
34            if(s[i-1]==s[j-1])
35                 next[i]=next[j];
36             else
37                 next[i]=j;
38        }
39        else
40             j=next[j];
41     }
42 }
43 
44 int KMP(int *s,int *t)
45 {
46     get_next(t,next);
47     int i=1;
48     int j=1;
49     //int len1=strlen(s);
50     //int len2=strlen(t);
51     int len1=N;
52     int len2=M;
53     while(i<=len1&&j<=len2)
54     {
55         if(j==0||s[i-1]==t[j-1])
56         {
57             i++;
58             j++;
59         }
60         else
61             j=next[j];
62     }
63     if(j>len2)
64         return i-len2-1;
65     else
66         return -1;
67 }
68 
69 
70 
71 int main()
72 {
73     int T;
74     scanf("%d",&T);
75     while(T--)
76     {
77         scanf("%d%d",&N,&M);
78         for(int i=0;i<N;i++)
79             scanf("%d",&str1[i]);
80         for(int i=0;i<M;i++)
81             scanf("%d",&str2[i]);
82         int ans=KMP(str1,str2);
83         printf("%d\n",ans>=0?ans+1:ans);
84     }
85     return 0;
86 }

 

posted @ 2015-02-27 12:00  daydaycode  阅读(133)  评论(0编辑  收藏  举报