首页 > 其他 > 详细

Inversions

时间:2014-07-22 22:53:44      阅读:501      评论:0      收藏:0      [点我收藏+]
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
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define MAXN 65540

using namespace std;

struct node
{
    long long v;
    int id;
    bool operator<(const node&p)const
    {return v<p.v;}
};
node a[MAXN+10];
long long c[MAXN+10];
long long b[MAXN+10];
int n;

long long lowbit(long long a)
{
    return a&(-a);
}

long long sum(long long a)
{
    long long s=0;
    while(a>0)
    {
        s+=c[a];
        a-=lowbit(a);
    }
    return s;
}

void update(long long a)
{
    while(a<=n+1)
    {
        c[a]++;
        a+=lowbit(a);
    }
}

int main(void)
{
    while(scanf("%d",&n)==1)
    {
        memset(a,0,sizeof(a));
        memset(c,0,sizeof(c));
        memset(b,0,sizeof(b));
        int i;
        for(i=1;i<=n;i++)
        {
            scanf("%lld",&(a[i].v));
            a[i].id=i;
        }
        sort(a+1,a+n+1);
        int pre=-1;
        int prevalue=0;
        for(i=1;i<=n;i++)
        {
            if(pre!=a[i].v)
            {
                pre=a[i].v;
                a[i].v=++prevalue;
            }
            else 
            {
                a[i].v=prevalue;
            }
        }
        for(i=1;i<=n;i++)
        {
            b[a[i].id]=a[i].v;
        }
        long long s=0;
        for(i=n;i>=1;i--)
        {
            update(b[i]);
            s+=sum(b[i]-1);
        }
        printf("%I64d\n",s);            
    }
    return 0;
}

 

Inversions,布布扣,bubuko.com

Inversions

原文:http://www.cnblogs.com/767355675hutaishi/p/3849100.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!