P13730 【MGVOI R1-B】完美重排(sort)

· · 个人记录

题目大意

给定一个排列 a,进行恰好一次完美重排操作(选择一个区间 [L, R] 并将区间内元素从小到大排序)。
有 Q 次询问,每次询问给定 x, y(x \le y),问有多少种重排方式使得原来在位置 x 的数在操作后出现在位置 y。

设 p = a[x]。

设区间 [L, R] 内有 k 个数比 p 小,则排序后 p 位于 L + k 处。
由 y = L + k 得 k = y - L。

定义 \text{pre}[i] 表示前 i 个数中小于 p 的个数,则

k = \text{pre}[R] - \text{pre}[L-1] = y - L \Rightarrow \text{pre}[R] = \text{pre}[L-1] + y - L

条件

满足以下条件的 [L, R] 即为合法操作:

  1. 1 \le L \le x \le R \le n
  2. \text{pre}[R] = \text{pre}[L-1] + y - L

做法

对每个询问:

  1. 根据 p = a[x] 计算 \text{pre}[0..n]
  2. 开一个桶,将 R \in [y, n] 对应的 \text{pre}[R] 加入桶中
  3. 枚举 L = 1 \dots x,计算目标值 t = \text{pre}[L-1] + y - L,累加桶中 t 的数量
  4. 清空桶(只清除本次加入的部分)

复杂度 O(nQ),适合 n 较小的数据范围。

代码


#include <bits/stdc++.h>
using namespace std;

const int N = 10010, B = 10000;

int n, q, a[N], pre[N], cnt[N*2];

int main() {
    scanf("%d%d", &n, &q);
    for (int i=1; i<=n; ++i) scanf("%d", &a[i]);

    while (q--) {
        int x, y;
        scanf("%d%d", &x, &y);
        int p = a[x];

        for (int i=1; i<=n; ++i) 
            pre[i] = pre[i-1] + (a[i] < p);

        for (int r=y; r<=n; ++r) cnt[pre[r]+B]++;

        long long ans = 0;
        for (int l=1; l<=x; ++l) 
            ans += cnt[pre[l-1] + y - l + B];

        for (int r=y; r<=n; ++r) cnt[pre[r]+B]--;

        printf("%lld\n", ans);
    }
    return 0;
}