跳到正文

个人记录

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

Columbula约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月17日
收录
2025年12月12日
更新
2026年11月10日
篇幅
约 3 分钟
题目
P13730

版本

  1. v1当前

题目大意

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


设 p=a[x]p = a[x]。

  • 若 xx 不在区间 [L,R][L, R] 内,则 pp 位置不变,只可能 x=yx = y。
  • 当 x<yx < y 时,必须有 L≤x≤RL \le x \le R。

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

定义 pre[i]\text{pre}[i] 表示前 ii 个数中小于 pp 的个数,则
k=pre[R]−pre[L−1]=y−Lk = \text{pre}[R] - \text{pre}[L-1] = y - L
⇒pre[R]=pre[L−1]+y−L\Rightarrow \text{pre}[R] = \text{pre}[L-1] + y - L

条件

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

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

做法

对每个询问:

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

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


代码

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