Input
5
3 1 2 4 5
Output
2
这道题的朴素做法是每个数遍历过去的同时再遍历该数的后面有多少比它小的数,统计起来即答案,但是这样的时间复杂度太大O(n^2),鉴于这个1e6的数据量,考虑O(nlogn)的做法。
考虑树状数组(修改和查询的复杂度都是O(nlogn)符合要求),因a[i]的范围可能很大,故需离散化。
离散化后原本是求数组a中的逆序对变成求数组d中的正序对。
如原序列:3 1 2 4 5 离散化后的序列:3 5 4 2 1
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
int a[N],d[N],tr[N],n;
int lowbit(int x)
{
return x&-x;
}
int add(int x)
{
while(x<=n)
{
tr[x]++;
x+=lowbit(x);
}
}
int sum(int x)
{
int res=0;
while(x)
{
res+=tr[x];
x-=lowbit(x);
}
return res;
}
bool cmp(int x,int y)
{
if(a[x]==a[y]) return x>y;//如果a中的该两元素相同 ,交换下标避免算上这两个数
return a[x]>a[y];//按照原序列的元素是第几大排序
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);//或者用scanf否则超时
long long ans=0;
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i],d[i]=i;//初始化原数组a和离散化后的数组d
sort(d+1,d+n+1,cmp);//离散化
for(int i=1;i<=n;i++)
{
add(d[i]);
ans+=sum(d[i]-1);//统计的d[i]前面有几个数比d[i]小的(不包括d[i]本身)
}
cout<<ans;
return 0;
}