思路:此题求逆序数的同时还要求逆序数的总和,对于s的逆序数个数可以用树状数组来求,再求s的逆序数的总和也可以用树状数组来解决
Code :
#include<iostream>
#include<cstring>
using namespace std;
typedef long long LL;
const int MAX_S=100005;
int n;
int Tree[MAX_S];
LL Sum[MAX_S];
int Lowbit(int x);
void Update(int id,int x,int p);
LL Query(int id,int p);
int main()
{
ios::sync_with_stdio(false);
while(cin>>n){
memset(Tree,0,sizeof(Tree));
memset(Sum,0,sizeof(Sum));
LL ans=0,x;
for(int i=1;i<=n;++i)
{
cin>>x;
Update(x,1,1); Update(x,x,0);
ans+=x*(i-Query(x,1))+Query(MAX_S-1,0)-Query(x,0);
}
cout<<ans<<endl;
}
return 0;
}
int Lowbit(int x)
{
return x&(-x);
}
void Update(int id,int x,int p)
{
while(id<MAX_S){
if(p) Tree[id]+=x;
else Sum[id]+=x;
id+=Lowbit(id);
}
}
LL Query(int id,int p)
{
LL ans=0;
while(id>0){
if(p) ans+=Tree[id];
else ans+=Sum[id];
id-=Lowbit(id);
}
return ans;
}