title Link:http://acm.hdu.edu.cn/showproblem.php?pid=1711
problem Description: give two sequence A, a, length of n,m (1<=n<=1000000,1<=m<=10000), and ask if sequence B is a sub-sequence of sequence A, if : Returns the first element subscript of the leftmost sub-sequence equal to B in a, if not , output-1.
purpose: Easy to view the template of next[] in KMP algorithm later
Number Sequence
Time limit:10000/5000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 12811 Accepted Submission (s): 5815
problem DescriptionGiven-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 is more than one K exist, output the smallest one.
InputThe first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is the 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 is in the range of [-1000000, 1000000].
OutputFor the test case, you should the output one line which only contain K described above. If No such K exists, output-1 instead.
Sample Input213 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 Output6-1
Code implementation:
1#include"stdio.h"2#include"string.h"3 #defineN 100054 5 intNext[n];6 inta[ -*N],b[n];7 8 voidKMP (int*s,intLenint*next)//request next[] Template9 {Ten inti,j; Onei =0; Aj = next[0] = -1; - while(i<len) - { the while(j!=-1&& s[i]!=S[j]) -j =Next[j]; -Next[++i] = + +J; - } + } - + intMain () A { at intT; - inti,j; - intn,m; -scanf"%d",&T); - while(t--) - { inscanf"%d%d",&n,&m); - for(i=0; i<n; i++) scanf ("%d",&a[i]); to for(i=0; i<m; i++) scanf ("%d",&b[i]); + KMP (b,m,next); -i=j=0; the while(i<N) * { $ while(j!=-1&& a[i]!=B[j])Panax Notoginsengj =Next[j]; -i++,j++; the if(j==m) Break; + } A if(j==m) printf ("%d\n", i-j+1);//The data in the title starts from subscript 1, so add 1 the Elseprintf"-1\n"); + } - return 0; $}
String _KMP algorithm (for next[] template Hdu 1711)