树状数组35pts 求助

P1908 逆序对

OK咯莫名其妙 @ 2021-07-20 15:17:48


#include<bits/stdc++.h>
using namespace std;
const int maxn=5e5+10;
long long n,ans;
long long c[maxn];

struct node{
    long long num,val;
};
node a[maxn];
long long lowbit(long long x){
    return x&(-x);
}
long long add(long long x,long long k)
{
    for(long long i=x;i<=n;i+=i&(-i)) c[i]+=k;
}
long long query(long long x)
{
    long long sum=0;
    for(long long i=x;i>0;i-=i&(-i)) sum+=c[i];
    return sum;
}
long long cmp(node a,node b){
    return a.val>b.val;
}
int main(){
    cin>>n;
    for(long long i=1;i<=n;i++)
        cin>>a[i].val,a[i].num=i;
    sort(a+1,a+n+1,cmp);
    for(long long i=1;i<=n;i++){
        add(a[i].num,1);
        ans+=query(a[i].num-1);
    }
    cout<<ans<<endl;
    return 0;
}

by 许江一墨 @ 2021-08-03 09:31:43

cmp 函数改成 >=

sort 改为 stable_sort

即可。


|