40 pts

P1908 逆序对

kind_aunt @ 2024-08-02 22:31:31

#include<bits/stdc++.h>
#define int long long 
using namespace std;
const int N=5e5+5;
int n;
int tree[N];
int ans;
struct node{
    int num,id,iid;
}a[N];
int lowbit(int x)
{
    return x&-x;
}
void update(int x)
{
    while(x<=N)
    {
        ++tree[x];
        x+=lowbit(x);
    }
}
int sum(int x)
{
    int ans=0;
    while(x)
    {
        ans+=tree[x];
        x-=lowbit(x);
    }
    return ans;
}
bool cmp1(node a,node b)
{
    return a.num<b.num;
}
bool cmp2(node a,node b)
{
    return a.id<b.id;
}
signed main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i].num;
        a[i].id=i;
    }
    sort(a+1,a+n+1,cmp1);
    for(int i=1;i<=n;i++)
        a[i].iid=i;
    sort(a+1,a+n+1,cmp2);
    for(int i=n;i;i--)
    {
        update(a[i].iid);
        ans+=sum(a[i].iid-1);
    }
    cout<<ans<<'\n';
    return 0;
}

|