HDU 1711: Number Sequence
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 1711: Number Sequence相关的知识,希望对你有一定的参考价值。
///@link http://acm.hdu.edu.cn/showproblem.php?pid=1711 ///@author Sycamore ///@date 8/19/2017 ///@ref stanford-acm-master #include <iostream> #include <string> #include <vector> using namespace std; typedef vector<int> VI; #define string VI #define length size void buildPi(string& p, VI& pi) { pi = VI(p.length()); int k = -2; for (int i = 0; i < p.length(); i++) { while (k >= -1 && p[k + 1] != p[i]) k = (k == -1) ? -2 : pi[k]; pi[i] = ++k; } } int KMP(string& t, string& p) { VI pi; buildPi(p, pi); int k = -1; for (int i = 0; i < t.length(); i++) { while (k >= -1 && p[k + 1] != t[i]) k = (k == -1) ? -2 : pi[k]; k++; if (k == p.length() - 1) { // p matches t[i-m+1, ..., i] //cout << "matched at index " << i - k << ": "; return i - k; k = (k == -1) ? -2 : pi[k]; } } return -1; } int main() { ios::sync_with_stdio(false); cin.tie(0); int T; cin >> T; while (T--) { int a_len, b_len; cin >> a_len >> b_len; VI a(a_len), b(b_len); for (auto &e : a)cin >> e; for (auto &e : b)cin >> e; int res = KMP(a, b); if (~res)cout << res + 1; else cout << -1; cout << ‘\n‘; } return 0; }
以上是关于HDU 1711: Number Sequence的主要内容,如果未能解决你的问题,请参考以下文章