HDU 1686: Oulipo
阿新 • • 發佈:2017-08-27
blue problem first required arr kmp longest size bsp
///@link http://acm.hdu.edu.cn/showproblem.php?pid=1686 ///@author Sycamore ///@date Aug, 27 #include <bits/stdc++.h> using namespace std; typedef vector<int> VI; //notations: //t - text //p - pattern //pi -an auxiliary array such that p[0,pi[i]] // is the longest suffix of p[0,i] VI getPi(const string& p) { VI pi = VI(p.length()); int k = -2; for (int i = 0; i < p.length(); i++) { //now k==p[i-1] while (k >= -1 && p[k + 1] != p[i])//find pi[i] using pi[i-1] k = (k == -1) ? -2 : pi[k];//make shifts pi[i] = ++k; } return pi; } int KMP(const string& t, const string& p) { int cnt = 0; VI pi = getPi(p); 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] //return i - k;//return if only the first match is required //output multiple matches//cout << "matched at index " << i - k << ": "; //cout << t.substr(i - k, p.length()) << endl; cnt++; k = (k == -1) ? -2 : pi[k]; } } return cnt; } int main() { ios::sync_with_stdio(false); cin.tie(0); int T; cin >> T; while (T--) { string p, t; cin >> p >> t; cout << KMP(t, p) <<‘\n‘; } return 0; }
HDU 1686: Oulipo