HDU 1711 Number Sequence kmp
Number SequenceTime Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission (s): 15821 Accepted Submission (s): 6978
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,100 0000].
Output For each test case, you shoshould 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
Source HDU 2007-Spring Programming Contest
Recommend lcy | We have carefully selected several similar problems for you: 1358 3336 1686 3746
ACcode
#include
# Include # Include # Include # Include # Include # Include # Include # define maxn 100 using namespace std; int N [1000000 + 10]; int M [10000 + 10]; int nex [10000 + 10]; int main () {int loop, la, lb; scanf (% d, & loop); while (loop --) {scanf (% d, & la, & lb ); for (int I = 0; I = 0 & M [pos]! = M [I-1]) pos = nex [pos]; nex [I] = + + pos;} int p = 0, cur = 0, t =-1; while (cur = 0) p = nex [p]; else {cur ++; p = 0;} if (p = lb) {t = cur-lb + 1; break ;}} printf (% d, t);} return 0 ;}