P13730 【MGVOI R1-B】完美重排(sort)
题目大意
给定一个排列
有
设
- 若
x 不在区间[L, R] 内,则p 位置不变,只可能x = y 。 - 当
x < y 时,必须有L \le x \le R 。
设区间
由
定义
条件
满足以下条件的
-
1 \le L \le x \le R \le n -
\text{pre}[R] = \text{pre}[L-1] + y - L
做法
对每个询问:
- 根据
p = a[x] 计算\text{pre}[0..n] - 开一个桶,将
R \in [y, n] 对应的\text{pre}[R] 加入桶中 - 枚举
L = 1 \dots x ,计算目标值t = \text{pre}[L-1] + y - L ,累加桶中t 的数量 - 清空桶(只清除本次加入的部分)
复杂度
代码
#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;
}