KMP-單次匹配
阿新 • • 發佈:2018-11-01
#include<bits/stdc++.h> using namespace std; #define N 1000005 int s[N]; int p[N]; int nxt[N]; int m, n; void getnext() { int j = 0, k = -1; nxt[0] = -1; while (j<m) { if (k == -1 || p[j] == p[k]) { j++; k++; nxt[j] = k; } else k = nxt[k]; } } int kmp() { int i = 0, j = 0; getnext(); while (i<n) { if (j == -1 || s[i] == p[j]) { i++; j++; } else j = nxt[j]; if (j == m) return i; } return -1; } int main() { int t; ios::sync_with_stdio(0);//這個一定要放在cin前面,且必須是cin,cout cin >> t; while (t--) { cin >> n >> m; for (int i = 0; i < n; i++) cin >> s[i]; for (int i = 0; i < m; i++) cin >> p[i]; if (kmp() == -1) cout << -1 << "\n"; else cout << kmp() - m + 1 << "\n"; } return 0; }