http://acm.hdu.edu.cn/showproblem.php?pid=1711
1 #include<iostream> 2 using namespace std; 3 int nx[10000+5], b[10000+5], a[1000000+5]; 4 int n, m; 5 void getnext(){ 6 int k = -1, j = 0; 7 nx[0] = -1; 8 while(j < m){ 9 if(k == -1 || b[j] == b[k]) nx[++j] = ++k; 10 else k = nx[k]; 11 } 12 } 13 int KMP() 14 { 15 int flag = -1; 16 for(int i = 0, j = 0; i < n; i++){ 17 while(j > 0 && b[j] != a[i]) j = nx[j]; 18 if(a[i] == b[j]) j++; 19 if(j == m) 20 { 21 return i - j + 2; 22 } 23 } 24 return -1; 25 } 26 int main() 27 { 28 ios::sync_with_stdio(0); 29 cin.tie(0); 30 cout.tie(0); 31 int t; 32 cin >> t; 33 while(t--){ 34 cin >> n >> m; 35 for(int i = 0; i < n; i++) cin >> a[i]; 36 for(int i = 0; i < m; i++) cin >> b[i]; 37 getnext(); 38 cout << KMP() << endl; 39 } 40 return 0; 41 }