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
Sample Output2 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
6 -1
题目大意:就是让你在第一个数组中找与第二个数组匹配的位置。
解题思路:因为是要最小的位置k,所以用kmp跑一遍,只要当第二数组跑到其长度停止。返回此时在第一个数组的位置,最后判断存不存在即可。
有一点,如果要用c++写的话需要关闭输入输出流,否则超时。。
/*
@Author: Top_Spirit
@Language: C++
*/
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std ;
typedef unsigned long long ull ;
typedef long long ll ;
const int Maxn = 1e6 + 10 ;
const int INF = 0x3f3f3f3f ;
const double PI = acos(-1.0) ;
const ull seed = 133 ;
int n, m ;
int Next[Maxn] ;
int a[Maxn], b[Maxn] ;
void getNext(){
Next[0] = -1 ;
int j = 0, k = -1 ;
while (j < m){
if (k == -1 || b[j] == b[k]) Next[++j] = ++k ;
else k = Next[k] ;
}
}
int KMP (){
int i = 0, j = 0 ;
while (i < n){
if (j == -1 || a[i] == b[j]){
i++ ;
j++ ;
}
else j = Next[j] ;
if (j == m) return i ;
}
return -1 ;
}
int main (){
ios_base :: sync_with_stdio(false) ;
cin.tie(0) ;
cout.tie(0) ;
int T ;
cin >> T ;
while (T--){
cin >> n >> m ;
for (int i = 0; i < n; i++) cin >> a[i] ;
for (int i = 0; i < m; i++) cin >> b[i] ;
getNext() ;
int ans = KMP() ;
if (ans == -1) cout << -1 << endl ;
else cout << ans - m + 1 << endl ;
}
return 0 ;
}