【题解】CF213E Two Permutations

题目传送门

前言

集训讲的一道高妙 DS。

前置芝士

平衡树,序列 Hash

分析

首先子序列并不是连续的一段,不好维护,考虑到给排列 \(a\) 每一项都加上 \(x\) 后在值域上依旧是连续的一段,所以我们记\(pos_{b_i} = i\),那么现在的问题就变成,我们每次从 \(pos\) 数组中选一个长度为 \(n\) 的子段,然后判断这个子段所对应的子序列是否和 \(a_i\) 变化后相同。

我们考虑用平衡树来维护序列,我们用 \((p, v)\) 来表示一个位置在 \(p\),值为 \(v\) 的点,然后每次以 \(p\) 为关键字插入,然后考虑判断序列相等,这里我们可以用序列 HASH 来快速判断,平衡树维护 Hash 是平凡的,而 \(a\) 排列每次 Hash 的增量也是好计算的,由于我们平衡树插入了一个哨兵,序列右移一维,所以在用 \(\text{Hash(A)} \times P\) 来判断。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <bits/stdc++.h>
#define ull unsigned long long

const int N = 2e5 + 10, P = 1331, INF = 1 <<30;
ull p[N], hasha, sump;
int pos[N];
struct Splay {
int s[2], p, sz, pos;
ull v, sum;
void init(ull _v, int _p, int _pos) {
v = sum = _v, p = _p, pos = _pos, sz = 1;
}
} t[N << 1];
int root, tot;

inline int read() {
int x = 0, y = 1; char c = getchar();
while (c < '0' || c > '9') {if (c == '-') y = -1; c = getchar();}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * y;
}

inline void pushup(int x) {
t[x].sz = t[t[x].s[0]].sz + t[t[x].s[1]].sz + 1;
t[x].sum = (t[t[x].s[0]].sum * P + t[x].v) * p[t[t[x].s[1]].sz] + t[t[x].s[1]].sum;
}

inline void rotate(int x) {
int y = t[x].p, z = t[y].p, k = t[y].s[1] == x;
t[z].s[t[z].s[1] == y] = x, t[x].p = z;
t[y].s[k] = t[x].s[!k], t[t[x].s[!k]].p = y;
t[x].s[!k] = y, t[y].p = x;
pushup(y), pushup(x);
}

inline void splay(int x, int k) {
while (t[x].p != k) {
int y = t[x].p, z = t[y].p;
if (z != k)
if ((t[z].s[1] == y) ^ (t[y].s[1] == x)) rotate(x);
else rotate(y);
rotate(x);
}
if (!k) root = x;
}

inline void insert(int pos, int v) {
int u = root, p = 0;
while (u) p = u, u = t[u].s[pos > t[u].pos];
u = ++tot;
if (p) t[p].s[pos > t[p].pos] = u;
t[u].init((ull)v, p, pos);
splay(u, 0);
}

inline void del(int pos) {
int u = root;
while (u) {
if (t[u].pos == pos) break;
else if (t[u].pos > pos) u = t[u].s[0];
else u = t[u].s[1];
}
splay(u, 0);
int l = t[u].s[0], r = t[u].s[1];
while (t[l].s[1]) l = t[l].s[1];
while (t[r].s[0]) r = t[r].s[0];
splay(l, 0), splay(r, l);
t[r].s[0] = 0;
pushup(r), pushup(l);
}

int main() {
int n = read(), m = read();
p[0] = sump = 1;
insert(-INF, 0), insert(INF, 0);
for (int i = 1; i <= 2e5; i++) p[i] = p[i - 1] * P;
for (int i = 1; i <= n - 1; i++) sump += p[i];
for (int i = 1; i <= n; i++) hasha = hasha * P + read();
for (int i = 1; i <= m; i++) pos[read()] = i;
for (int i = 1; i <= n - 1; i++) insert(pos[i], i);
int res = 0;
for (int i = n; i <= m; i++) {
insert(pos[i], i);
if (t[root].sum == hasha * P) res++;
hasha += sump;
del(pos[i - n + 1]);
}
printf("%d\n", res);
return 0;
}