SGU180 Inversions 离散 + 树状数组

本文介绍了一种利用树状数组进行逆序对计数的方法,适用于离散化的整数集合。通过输入一系列整数,该算法能高效计算出所有逆序对的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There are N integers (1<=N<=65537) A1, A2,.. AN (0<=Ai<=10^9). You need to find amount of such pairs (i, j) that 1<=i<j<=N and A[i]>A[j].
Input

The first line of the input contains the number N. The second line contains N numbers A1...AN.
Output

Write amount of such pairs.
Sample test(s)
Input


2 3 1 5 4

Output

3

题解:离散化之后树状数组统计求和即可。

AC代码:

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define _for(i,a,b) for(int i=a;i<=b;i++)
typedef long long ll;
const int maxn = 70000;
struct node
{
    int id,num;
    bool operator<(const node& a)const
    {
        return num<a.num;
    }
}a[maxn];
int n,b[maxn];
ll c[maxn];
int lowbit(int x)
{
    return x&(-x);
}
void update(int x)
{
    while(x<=n)
    {
        c[x]++;
        x+=lowbit(x);
    }
}
ll sum(int x)
{
    ll now = 0;
    while(x>0)
    {
        now+=c[x];
        x-=lowbit(x);
    }
    return now;
}
int main(int argc, char const *argv[])
{
    cin>>n;
    _for(i,1,n)
    {
        cin>>a[i].num;
        a[i].id=i;
   }
    sort(a+1,a+1+n);
    b[a[1].id]=1;
    _for(i,2,n)
    {
        if(a[i].num!=a[i-1].num)b[a[i].id]=i;
        else b[a[i].id]=b[a[i-1].id];
    }
    ll ans = 0;
    _for(i,1,n)
    {
        update(b[i]);
        ans+=sum(n)-sum(b[i]);
    }
    cout<<ans<<endl;        
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值