高级数据结构第六章A . 逆序对

image

代码:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>


using namespace std;
typedef long long LL;

const int N = 1e5+10;

LL tr[N],n,a[N];
vector<LL>nums;

LL lowbit(int x)
{
    return x & -x;
}

void update(int x, int c)  
{
    for (int i = x; i <= n; i += lowbit(i)) tr[i] += c;
}
LL query(int x)  
{
    int res = 0;
    for (int i = x; i; i -= lowbit(i)) res += tr[i];
    return res;
}


int main()
{
    cin>>n;    
    for (int i = 1; i <= n; i ++ ) cin>>a[i],nums.push_back(a[i]);
    sort(nums.begin(),nums.end());
    nums.erase(unique(nums.begin(),nums.end()),nums.end());
    int m=nums.size();
   // cout<<m<<endl;
    LL res=0;
    for (int i = 1; i <= n; i ++ ){
        int tmp=lower_bound(nums.begin(),nums.end(),a[i])-nums.begin()+1;
        res+=query(m)-query(tmp);
        update(tmp,1);
    }
    cout<<res<<endl;
    
    return 0;
}

posted @ 2021-06-13 20:46  OvO1  阅读(51)  评论(0编辑  收藏  举报