简单的KMP
好吧好吧
还是花了一上午
next[0] =-1
还是看注释吧
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 using namespace std; 3 4 int T[1000005];//不明白自己动态分配的话就会ACCESS_VIOLENCE 5 int P[10005];//不管了以后都写外面好了 6 int next[10005]; 7 8 int main() 9 { 10 int t; 11 cin >> t; 12 while (t--) 13 { 14 int M, N; 15 cin >> N >> M; 16 17 for (int i = 0; i < N; i++) 18 { 19 cin >> T[i]; 20 } 21 22 for (int i = 0; i < M; i++) 23 { 24 cin >> P[i]; 25 } 26 27 for (int i = 0; i < 10005; i++) 28 { 29 next[i] = 0; 30 } 31 32 for (int i = 1; i < M; i++)//获得next数组 33 { 34 int j = next[i]; 35 while (j&&P[i] != P[j])//如果不相同就循环一直到j=0或者找到j使得P[i]=P[j]; 36 j = next[j]; 37 next[i + 1] = (P[i] == P[j] ? j + 1 : 0);//递归获得next 38 } 39 // next[0] 设置为 -1 40 next[0] = -1; 41 int ans = -1; 42 int j = 0; 43 if (M == 1)//m长为1时 44 { 45 for (int i = 0; i < N; i++) 46 { 47 if (T[i] == P[j]) 48 { 49 ans = i + 1; 50 break; 51 } 52 } 53 } 54 else 55 { 56 for (int i = 0; i<N; i++) 57 { 58 // j > -1 , 保证完全匹配失败的时候,j能返回到0 59 while (j > -1 && T[i] != P[j]) 60 j = next[j]; 61 j++; 62 if (j == M) { 63 ans = i - M + 1 + 1; 64 break; 65 } 66 } 67 } 68 69 cout << ans << endl; 70 } 71 return 0; 72 }