题解:P12685 [国家集训队] 排队 加强版
SegmentTree_ · · 题解
很暴力的分块做法。
离散化后,对序列和值域分别分块。用
对于一个位置
把交换拆成两次单点修改。单点修改时,直接减掉原身高的贡献,再加上新身高的贡献,同时维护
原序列的逆序对可以用树状数组求,也可以预处理
#include <bits/stdc++.h>
using namespace std;
#define ll long long
typedef pair<int, int> pii;
const int N = 2e5+5;
namespace tianyu{
const int B = 1000, BT = (N - 1) / B + 3;
int n, m;
int a[N], b[N], bel[N], bl[BT], br[BT], bt;
int cnt1[BT][BT], cnt2[BT][N];
ll now = 0;
void modify(int p, int x){
int X = bel[p], V = bel[a[p]];
for (int i = V + 1;i <= bt;i++) now -= cnt1[X - 1][i];
for (int i = a[p] + 1;i <= br[V];i++) now -= cnt2[X - 1][i];
for (int i = 1;i < V;i++) now -= cnt1[bt][i] - cnt1[X][i];
for (int i = bl[V];i < a[p];i++) now -= cnt2[bt][i] - cnt2[X][i];
for (int i = bl[X];i < p;i++) now -= (a[i] > a[p]);
for (int i = p + 1;i <= br[X];i++) now -= (a[p] > a[i]);
V = bel[x];
for (int i = V + 1;i <= bt;i++) now += cnt1[X - 1][i];
for (int i = x + 1;i <= br[V];i++) now += cnt2[X - 1][i];
for (int i = 1;i < V;i++) now += cnt1[bt][i] - cnt1[X][i];
for (int i = bl[V];i < x;i++) now += cnt2[bt][i] - cnt2[X][i];
for (int i = bl[X];i < p;i++) now += (a[i] > x);
for (int i = p + 1;i <= br[X];i++) now += (x > a[i]);
for (int i = X;i <= bt;i++){
cnt1[i][bel[a[p]]]--;
cnt2[i][a[p]]--;
cnt1[i][bel[x]]++;
cnt2[i][x]++;
}
a[p] = x;
}
void awa(){
cin >> n;
for (int i = 1;i <= n;i++) cin >> a[i], b[i] = a[i];
sort(b + 1, b + 1 + n);
for (int i = 1;i <= n;i++) a[i] = lower_bound(b + 1, b + 1 + n, a[i]) - b;
for (int i = 1;i <= n;i++) bel[i] = (i - 1) / B + 1;
bt = bel[n];
for (int i = 1;i <= bt;i++) bl[i] = (i - 1) * B + 1, br[i] = i * B;
br[bt] = n;
for (int i = 1;i <= bt;i++){
for (int j = bl[i];j <= br[i];j++){
cnt1[i][bel[a[j]]]++;
cnt2[i][a[j]]++;
for (int k = bl[i];k < j;k++) now += (a[k] > a[j]);
for (int k = bel[a[j]] + 1;k <= bt;k++) now += cnt1[i - 1][k];
for (int k = a[j] + 1;k <= br[bel[a[j]]];k++) now += cnt2[i - 1][k];
}
for (int j = 1;j <= n;j++) cnt2[i][j] += cnt2[i - 1][j];
for (int j = 1;j <= bt;j++) cnt1[i][j] += cnt1[i - 1][j];
}
cout << now << '\n';
cin >> m;
while (m--){
int x, y;
cin >> x >> y;
auto [u, v] = pii{a[x], a[y]};
modify(x, v);
modify(y, u);
cout << now << '\n';
}
}
}
signed main(){
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int T = 1;
while (T--) tianyu::awa();
return 0;
}