CF193D Two Segments 题解
要这个排列构成连续段,那直接维护下标无疑是困难的,于是考虑维护数列中对应的值
考虑加入元素
实际实现的时候我们不需要维护次小值,因为本题里显然次小值就等于最小值
代码:
#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;
}
分类:
题解
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律