本人双非铜牌选手,入坑ACM6个月,目前板刷CF来提升自己的算法能力和代码实现能力,欢迎关注我一起刷题QwQ。本人CF账号
tag:树状数组,离散化
problem types:求最值
求逆序对->树状数组
a范围1e9->离散化
如何在离散化的树状数组中求逆序对?
在原数组中二分查找,得到index,index大小比较就是原数大小比较
#include<bits/stdc++.h>
using namespace std;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define int long long
const int N = 2e5 + 10;
int a[N], b[N], tr[N];
int n;
int lowbit(int x){
return x & -x;
}
void add(int pos, int x){
while(pos <= n){
tr[pos] += x;
pos += lowbit(pos);
}
}
int cal(int x){
int res = 0;
while(x >= 1){
res += tr[x];
x -= lowbit(x);
}
return res;
}
void solve() {
cin >> n;
rep(i, 1, n) tr[i] = 0;
rep(i, 1, n){
cin >> a[i];
b[i] = a[i];
}
sort(a + 1, a + n + 1);
int len = unique(a + 1, a + n + 1) - a - 1;
rep(i, 1, n){
b[i] = lower_bound(a + 1, a + 1 + len, b[i]) - a;
}
int res = 0;
rep(i, 1, n){
int tmp = b[i];
add(tmp, 1);
int check1 = cal(n) - cal(tmp);
int check2 = cal(tmp - 1);
res += min(check1, check2);
}
cout << res << '\n';
}
signed main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while(t--) {
solve();
}
}