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.
InputThe 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].
OutputFor 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
题意:KMP找第一次出现模式串的位次,也可以用strstr之类的函数找出。
题解:KMP模板
代码:
#include <iostream> #include <cstring> #include <string> #include <vector> using namespace std; const int N = 1000002; int nextt[N]; //string S,T; vector<int>S,T; int slen, tlen; void getNext() { int j, k; j = 0; k = -1; nextt[0] = -1; while(j < tlen) if(k == -1 || T[j] == T[k]) nextt[++j] = ++k; else k = nextt[k]; } /* 返回模式串T在主串S中首次出现的位置 返回的位置是从0开始的。 */ int KMP_Index() { int i = 0, j = 0,ans=-1; getNext(); while(i < slen && j < tlen) { if(j == -1 || S[i] == T[j]) { i++; j++; } else j = nextt[j]; if(j == tlen){ //ans++;// ans=i-j; //j=0;// break; } } return ans; } int main() { int TT; int i, cc; cin>>TT; while(TT--) { int s1,s2; int temp; cin>>s1>>s2; S.clear(); T.clear(); while(s1--){ scanf("%d", &temp); S.push_back(temp); } while(s2--){ scanf("%d", &temp); T.push_back(temp); } slen = S.size(); tlen = T.size(); int ccnt=KMP_Index(); if(ccnt!=-1)ccnt++; cout<<ccnt<<endl; } return 0; }