标签:which line 序列 oid include nbsp make ane inpu
1 #include<iostream> 2 #include<algorithm> 3 #include<cstring> 4 #include<string> 5 6 using namespace std; 7 const int maxn = 1000005; 8 int rs[4][4], nex[maxn], a[maxn], b[maxn/100 + 5], n, m; 9 void cal_next(int *str, int len) 10 { 11 nex[0] = -1; int k = -1; 12 for (int i = 1; i <= len - 1; i++) { 13 while (k > -1 && str[k + 1] != str[i]) 14 k = nex[k]; 15 if (str[k + 1] == str[i])k = k + 1; 16 nex[i] = k; 17 } 18 } 19 int KMP(int *a, int la, int *b, int lb) 20 { 21 cal_next(b , lb); 22 int k = -1; 23 for (int i = 0; i < la; i++) { 24 while (k > -1 && b[k + 1] != a[i]) 25 k = nex[k]; 26 if (b[k + 1] == a[i])k = k + 1; 27 if (k == lb - 1)return i - lb + 1; 28 } 29 return -1; 30 } 31 int main() 32 { 33 ios::sync_with_stdio(false); 34 int T; 35 cin >> T; 36 while (T--) { 37 cin >> n >> m; 38 for (int i = 0; i < n; i++)cin >> a[i]; 39 for (int i = 0; i < m; i++)cin >> b[i]; 40 int ans = KMP(a, n, b, m); 41 if (ans != -1)cout << ans + 1 << endl; 42 else cout << "-1" << endl; 43 } 44 return 0; 45 }
HDU 1711 Number Sequence (KMP 入门)
标签:which line 序列 oid include nbsp make ane inpu
原文地址:https://www.cnblogs.com/wangrunhu/p/9526854.html