CF193D Two Segments 题解

CF193D Two Segments 题解

要这个排列构成连续段,那直接维护下标无疑是困难的,于是考虑维护数列中对应的值 [l,r]。暴力维护的区间个数是 O(n2) 的,考虑常见的优化套路:将 r 扫描线,维护 [1,r1]l 的贡献。

考虑加入元素 ai 后对块数的贡献:我们可以认为起初 ai 一开始新建了一块。当选择了 ai1 时,块数会减少 1;选择了 ai+1 时,同理。那么对于选择左端点在 [1,ai1] 时的块数贡献应该 1,在 [1,ai+1] 时同理。这样一来我们需要一个区间加区间查的线段树维护区间最小值,次小值以及其分别的出现次数,维护这些是容易的。

实际实现的时候我们不需要维护次小值,因为本题里显然次小值就等于最小值 +1

代码:

#include <bits/stdc++.h>
#define N 300005
#define int long long
using namespace std;
int n;
int a[N];
struct Node {
	int l, r;
	int mn, tg;
	int p1, p2;
} e[N << 2];
#define l(i) e[i].l
#define r(i) e[i].r
#define mn(i) e[i].mn
#define tg(i) e[i].tg
#define p1(i) e[i].p1
#define p2(i) e[i].p2
#define lc (p << 1)
#define rc (lc | 1)
void push_up(int p) {
	mn(p) = min(mn(lc), mn(rc));
	p1(p) = p1(lc) * (mn(p) == mn(lc)) + p1(rc) * (mn(p) == mn(rc));
	p2(p) = p1(lc) * (mn(p) + 1 == mn(lc)) + p1(rc) * (mn(p) + 1 == mn(rc)) + p2(lc) * (mn(p) == mn(lc)) + p2(rc) * (mn(p) == mn(rc));
}
void build(int p, int l, int r) {
	l(p) = l, r(p) = r;
	if (l == r) return p1(p) = 1, void();
	int mid = (l + r) >> 1;
	build(lc, l, mid);
	build(rc, mid + 1, r);
}
void push_down(int p) {
	if (tg(p) == 0) return;
	mn(lc) += tg(p);
	mn(rc) += tg(p);
	tg(lc) += tg(p);
	tg(rc) += tg(p);
	tg(p) = 0;
	return;
}
void update(int p, int l, int r, int x) {
	if (l > r || l > r(p) || l(p) > r) return;
	if (l <= l(p) && r(p) <= r) {
		mn(p) += x;
		tg(p) += x;
		return;
	}
	push_down(p);
	update(lc, l, r, x);
	update(rc, l, r, x);
	push_up(p);
}
int query(int p, int l, int r) {
	if (l > r || l > r(p) || l(p) > r) return 0;
	if (l <= l(p) && r(p) <= r) return (mn(p) <= 2) * p1(p) + (mn(p) <= 1) * p2(p);
	push_down(p);
	return query(lc, l, r) + query(rc, l, r);
}

int p[N], ans;
signed main() {
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i], p[a[i]] = i;
	build(1, 1, n);
	for (int i = 1; i <= n; i++) {
		update(1, 1, i, 1);
		if (a[p[i] - 1] < i) update(1, 1, a[p[i] - 1], -1);
		if (a[p[i] + 1] < i) update(1, 1, a[p[i] + 1], -1);
		ans += query(1, 1, i - 1);
	}
	cout << ans << '\n';
	return 0;
}
posted @   长安19路  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示