跳到正文

题解

P10798 题解

Cwkapn约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年8月10日
收录
2026年8月11日
更新
2026年11月21日
篇幅
约 5 分钟
题目
P10798

版本

  1. v1当前

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

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

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

代码
3 2 1 2 3 1 3

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

代码
3 2 1 2 -3 1 -3

然后对 22 做操作,得:

代码
3 2 1 -2 -3 1 -3

11 不需要做操作,因为没有以 11 为端点的威胁区间,同理第 44 个数 −2-2 也不需要。接下来对第 55 个数做操作:

代码
3 2 1 -2 -3 1 3

可以发现,最右侧曾变成 −3-3 的 33 现在又变回了 33。但即使这样,操作仍然会最小化威胁区间数量,因为虽然以第 11 个数为左端点的威胁区间在这一步操作多了 11 个,但以第 55 个数为左端点的威胁区间也减少了 11 个,这样操作总威胁区间数一定没有增多。

因此,只需要对每个数统计它与它左侧第一个比它大的数之间,和它相等的数个数,然后按奇偶性赋符号即可。为此,可以用树状数组等数据结构维护:自上次遇到比这个 ii 大的数以来,ii 出现的次数。只需要每添加一个数就把所有比它小的都清除即可。这样做的时间复杂度为 O(nlog⁡n)\mathcal{O}(n \log n)。注意离散化、特判 00。

C++
#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;
}
原文