题解:CF213E Two Permutations
block_in_mc · · 题解
提供一个
我们称两个排列
由于
可以发现,这个条件等价于
具体地,我们需要对于排列
唯一与普通 KMP 不同的地方在于匹配完前
总时间复杂度
#include <bits/stdc++.h>
using namespace std;
const int N = 200100;
int n, m, ans, a[N], b[N], p[N], t[N], ls[N], rs[N], fail[N];
stack<int> st;
bool chk(int *x, int i, int k) {
int s = i - k + 1;
if (ls[k] && !(x[s + ls[k] - 1] < x[i])) return false;
if (rs[k] && !(x[i] < x[s + rs[k] - 1])) return false;
return true;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> a[i], p[a[i]] = i;
for (int i = 1; i <= m; i++)
cin >> b[i], t[b[i]] = i;
st.push(0);
for (int i = 1; i <= n; i++){
while (st.top() > a[i]) st.pop();
ls[a[i]] = st.top();
st.push(a[i]);
}
while (!st.empty()) st.pop();
st.push(0);
for (int i = n; i >= 1; i--){
while (st.top() > a[i]) st.pop();
rs[a[i]] = st.top();
st.push(a[i]);
}
for (int i = 2, j = 0; i <= n; i++) {
while (j && !chk(p, i, j + 1)) j = fail[j];
if (chk(p, i, j + 1)) j++;
fail[i] = j;
}
for (int i = 1, j = 0; i <= m; i++) {
while (j && !chk(t, i, j + 1)) j = fail[j];
if (chk(t, i, j + 1)) j++;
if (j == n) ans++, j = fail[j];
}
cout << ans;
return 0;
}