Sol
这篇题解很大程度上参考了当前第一篇,并证明了其它没有提到的正确性。
下面记一个点
考虑一个很牛的 trick: 对于一个连通块,设定一个唯一的代表元,那么连通块的个数就可以用代表元的个数来表示。
最小的点是最有可能黑的,假设一个连通块中
首先考虑第一项更小的点,设
比如
读到这里读者肯定会有疑问,为什么一定走直线呢?假设走了曲线,比如先从
移项,和
时间复杂度
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
const int N = 2e5 + 10, inf = 1 << 30;
template<typename T>
void dbg(const T &t) { cout << t << endl; }
template<typename Type, typename... Types>
void dbg(const Type& arg, const Types&... args) {
cout << arg << ' ';
dbg(args...);
}
int n, m, x, a[N], b[N], st[20][N], stk[N], top, l[N], r[N], tot;
ll ans;
struct Node {
int x, y, typ;
bool operator < (const Node &A) const {
return {x == A.x ? typ > A.typ : x > A.x};
}
} c[N << 1];
struct Fenwick {
#define lowbit(x) (x & -x)
int n, tr[N];
void add(int x, int v) { while (x <= n) { tr[x] += v; x += lowbit(x); } }
int ask(int x) { int res = 0; while (x > 0) { res += tr[x]; x -= lowbit(x); } return res; }
} BIT;
int query(int l, int r, int up) {
if (!l || r == up + 1) return inf;
int x = __lg(r - l + 1);
return max(st[x][l], st[x][r - (1 << x) + 1]);
}
void init() {
for (int i = 1; i <= n; i++) st[0][i] = a[i];
for (int d = 1; d < 20; d++) for (int i = 1; i <= n - (1 << d) + 1; i++) st[d][i] = max(st[d - 1][i], st[d - 1][i + (1 << (d - 1))]);
top = 0; stk[top] = 0;
for (int i = 1; i <= n; i++) {
while (top && a[stk[top]] > a[i]) top--;
l[i] = stk[top]; stk[++top] = i;
}
top = 0; stk[top] = n + 1; // r[i] 为 0 时变为 n + 1
for (int i = n; i; i--) {
while (top && a[stk[top]] >= a[i]) top--;
r[i] = stk[top]; stk[++top] = i;
}
for (int i = 1; i <= n; i++) c[++tot] = {min(query(l[i], i, n), query(i, r[i], n)), a[i], 0};
for (int i = 1; i <= m; i++) st[0][i] = b[i];
for (int d = 1; d < 20; d++) for (int i = 1; i <= m - (1 << d) + 1; i++) st[d][i] = max(st[d - 1][i], st[d - 1][i + (1 << (d - 1))]);
top = 0; stk[top] = 0;
for (int i = 1; i <= m; i++) {
while (top && b[stk[top]] > b[i]) top--;
l[i] = stk[top]; stk[++top] = i;
}
top = 0; stk[top] = m + 1;
for (int i = m; i; i--) {
while (top && b[stk[top]] >= b[i]) top--;
r[i] = stk[top]; stk[++top] = i;
}
for (int i = 1; i <= m; i++) c[++tot] = {x - b[i], x - min(query(l[i], i, m), query(i, r[i], m)), 1};
}
void solve() {
sort(c + 1, c + tot + 1);
for (int i = 1; i <= tot; i++) {
auto [x, y, typ] = c[i];
if (typ) {
ans += BIT.ask(x) - BIT.ask(y);
} else BIT.add(y, 1);
}
}
int main() {
// freopen("data.in", "r", stdin);
// freopen("data.out", "w", stdout);
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> m >> x; BIT.n = x;
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= m; i++) cin >> b[i];
init(); solve();
cout << ans << '\n';
return 0;
}