P10798 题解

· · 题解

这种思路好像题解区里还没有。

首先不妨对序列中每个数求绝对值,因为这样做不改变答案。考虑以第 i 个数为右端点的威胁区间数量:这些威胁区间的左端点都等于 A_i,且左端点与 i 之间没有大于 A_i 的数。

为了最小化威胁区间的数量,可以对每个左端点的所有右端点取相反数以消除这些威胁区间。但对于同一个右端点,可能被很多个左端点取了相反数,比如对于:

3 2 1 2 3 1 3

先对最左侧 3 做如上操作,得:

3 2 1 2 -3 1 -3

然后对 2 做操作,得:

3 2 1 -2 -3 1 -3
``` 3 2 1 -2 -3 1 3 ``` 可以发现,最右侧曾变成 $-3$ 的 $3$ 现在又变回了 $3$。但即使这样,操作仍然会最小化威胁区间数量,因为虽然以第 $1$ 个数为左端点的威胁区间在这一步操作多了 $1$ 个,但以第 $5$ 个数为左端点的威胁区间也减少了 $1$ 个,这样操作总威胁区间数一定没有增多。 因此,只需要对每个数统计它与它左侧第一个比它大的数之间,和它相等的数个数,然后按奇偶性赋符号即可。为此,可以用树状数组等数据结构维护:自上次遇到比这个 $i$ 大的数以来,$i$ 出现的次数。只需要每添加一个数就把所有比它小的都清除即可。这样做的时间复杂度为 $\mathcal{O}(n \log n)$。注意离散化、特判 $0$。 ```cpp #include <bits/stdc++.h> using namespace std; #define gc getchar template<typename T> void read(T &x) { char c = gc(); int f = 1; x = 0; while (!isdigit(c)) f = (c == '-' ? -f : f), c = gc(); while (isdigit(c)) x = (x << 3) + (x << 1) + c - '0', c = gc(); x *= f; } template<typename T, typename ... Args> void read(T &x, Args& ... args) {read(x); read(args...);} #define rep(i, s, t) for(int i=(s);i<=(t);i++) #define per(i, s, t) for(int i=(s);i>=(t);i--) #define ll long long #define ull unsigned long long #define pii pair<int,int> #define lll __int128 template<typename T> void chkmx(T &x, const T &y) {x = max(x, y);} template<typename T> void chkmn(T &x, const T &y) {x = min(x, y);} const int N = 500005; #define lowbit(x) ((x)&-x) int n, a[N], s[N], sgn[N], b[N], cnt[N][2]; queue<int> q; set<int> st; void add(int x, int y) { while (x <= n) { s[x] += y; x += lowbit(x); } } int query(int x) { int res = 0; while (x) { res += s[x]; x -= lowbit(x); } return res; } int main() { read(n); rep(i, 1, n) { read(a[i]); a[i] = abs(a[i]); b[i] = a[i]; } sort(b + 1, b + n + 1); int tot = unique(b + 1, b + n + 1) - b - 1; rep(i, 1, n) a[i] = lower_bound(b + 1, b + n + 1, a[i]) - b; rep(i, 1, n) { sgn[i] = ((query(a[i]) - query(a[i] - 1)) % 2); if (b[a[i]] == 0) sgn[i] = 0; while (!st.empty() && (*st.begin()) < a[i]) { add(*st.begin(), -query(*st.begin())); st.erase(st.begin()); } add(a[i], 1); st.insert(a[i]); } rep(i, 1, n) add(i, -query(i)); ll ans = 0; rep(i, 1, n) { ans += cnt[a[i]][sgn[i]]; while (!st.empty() && (*st.begin()) < a[i]) { cnt[*st.begin()][0] = cnt[*st.begin()][1] = 0; st.erase(st.begin()); } cnt[a[i]][sgn[i]]++; st.insert(a[i]); } printf("%lld\n", ans); return 0; } ```