SGU 180 - Inversions(逆序数)

180. Inversions
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
input: standard
output: standard

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


逆序数对,树状数组+离散化

离散化方法:http://blog.csdn.net/gokou_ruri/article/details/7723378

先离散化使数据密集,然后对每个数进行处理,一个一个插入树状数组。比如插入一个数a[i],就更新一遍a[i]置的值,也就是+1,表示出现了一个数字a[i]。Query(a[i])是当前小于等于a[i]的所有数的出现次数,也就是之前插入的数中有多少小于等于a[i],那么 i-Query(a[i]) 就是当前大于a[i]的数的个数,是满足答案的解,加到sum中。

注意sum要定义成long long


#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn=70000;
int tree[maxn],n,a[maxn],b[maxn];
int Lowbit(int i)
{
    return i&(-i);
}

void Update(int i,int x)
{
    while(i<=n)
    {
        tree[i]+=x;
        i+=Lowbit(i);
    }
}

int Query(int i)
{
    int sum=0;
    while(i>0)
    {
        sum+=tree[i];
        i-=Lowbit(i);
    }
    return sum;
}

int main()
{
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
        b[i]=a[i];
    }
    sort(b,b+n);
    int size=unique(b,b+n)-b;
    long long sum=0;
    for(int i=0;i<n;i++)
    {
        int pos=upper_bound(b,b+size,a[i])-b;
        Update(pos,1);
        sum+=i+1-Query(pos);
    }
    printf("%I64d\n",sum);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值