题解:CF1637H Minimize Inversions Number
题目的这个操作有点复杂,我们先从简单的情况入手。对于
证明显然。设选
对于要选多个数来说,直接算
其中
我们终于把答案写出来了,但是这个东西还不能直接求,需要先发掘一些性质。就最简单的直觉上来看,一定要尽量地破坏原本的逆序对,也就是说若
进一步地,答案可化为:
设求和号里的部分为
时间复杂度为
代码如下:
#include <bits/stdc++.h>
#define int long long
#define pb push_back
#define file(x) freopen(#x ".in", "r", stdin); freopen(#x ".out", "w", stdout);
using namespace std;
constexpr int N = 5e5 + 5;
int t, n, a[N], tree[N], c[N], ans;
int lowbit(int x) { return x & (-x); }
void modify(int x) { for (int i = x; i <= n; i += lowbit(i)) ++tree[i]; }
int query(int x) { int ret = 0; for (int i = x; i; i -= lowbit(i)) ret += tree[i]; return ret; }
signed main() {
cin.tie(0) -> sync_with_stdio(false);
cin >> t;
while(t--) {
cin >> n, ans = 0;
fill(tree, tree + n + 1, 0);
for (int i = 1; i <= n; ++i) cin >> a[i], c[i] = i - (a[i] << 1);
for (int i = n; i >= 1; --i) ans += query(a[i]), modify(a[i]);
sort(c + 1, c + n + 1, greater <int> ());
cout << ans << ' ';
for (int i = 1; i <= n; ++i) cout << (ans -= i + c[i]) << ' ';
cout << '\n';
}
}