题意:
给你一个长度为 $ n $ 的数组,求其中的逆序对数量。
解法:
数据范围很大 $ (n \leq 5 \times 10^5) $ ,所以考虑离散化+树状数组。
CODE:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
#define LL long long
const int N = 5e5 + 100;
struct Node {
int val,pos;
} a[N];
int tree[N],tag[N],n;
LL ans;
inline int lowbit(int x) {
return x & (-x);
}
inline void add(int x) {
for(; x <= n ; x += lowbit(x))
tree[x]++;
return;
}
inline int query(int x) {
int ans = 0;
for(; x ; x -= lowbit(x))
ans += tree[x];
return ans;
}
inline bool cmp(Node a,Node b) {
if(a.val == b.val)
return a.pos < b.pos;
return a.val < b.val;
}
inline int read() {
int x = 0,f = 1;
char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f=-1; ch=getchar();}
while(ch >= '0' && ch <= '9') {x = (x<<1) + (x<<3) + (ch^48);ch = getchar();}
return x * f;
}
int main() {
n = read();
for(int i = 1 ; i <= n ; i++) {
a[i].val = read();
a[i].pos = i;
}
sort(a + 1,a + n + 1,cmp);
for(int i = 1 ; i <= n ; i++) tag[a[i].pos] = i;
for(int i = n ; i >= 1 ; i--) {
ans += query(tag[i]);
add(tag[i]);
}
printf("%lld \n",ans);
//system("pause");
return 0;
}