题目描述
思路:
我们可以由归并排序过程可得,每交换一次就消除一个逆序对,所以操作数就是逆序对个数
这里用树状数组求,按照输入进来的顺序,用树状数组统计就可以了
c o d e code code
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
long long n, a[1010000];
long long c[1010000];
long long lowbit(long long x)
{
return x & -x;
}
void add(long long x, long long y)
{
for(; x<=200001; x+=lowbit(x))
{
c[x]+=y;
}
}
long long query(long long x)
{
long long ans=0;
for(; x; x-=lowbit(x))
{
ans+=c[x];
}
return ans;
}
int main()
{
scanf("%lld", &n);
for(long long i=1; i<=n; i++)
{
scanf("%lld", &a[i]);
a[i]++;
}
long long ans=0;
for(long long i=1; i<=n; i++)
{
ans+=query(200001)-query(a[i]);
add(a[i], 1);
}
printf("%lld", ans);
return 0;
}