题目大意:假定给你一段数字序列,数字大小从0 - n-1, 求其中满足(a[i]>a[j]&&i<j)的逆序对的数量

分析:利用树状数组维护一个前缀和数组,对于每个元素,将其所在位置加一,c[i]既是在i之前比a[i]小的数的数量。

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1000;
int c[N], a[N];
int n;
int lowbit(int x){
return x&-x;
}
void update(int x){
while(x <= n){
c[x]++;
x += lowbit(x);
}
}
int query(int x){
int ans = 0;
while(x > 0){
ans += c[x];
x -= lowbit(x);
}
return ans;
}

int main()
{
while(~scanf("%d", &n)){
memset(c, 0, sizeof(c));
int res = 0;
for(int i = 1; i <= n; i++){
scanf("%d", &a[i]);
a[i]++;
}
int left, right;
for(int i = 1; i <= n; i++){
left = query(a[i]); //i之前比a[i]小的数的数量
right = i - 1 - left; //i之前比a[i]大得数的数量
res+= right;
update(a[i]);
}
cout << res << endl;
}
return 0;
}