码迷,mamicode.com
首页 > 其他好文 > 详细

Inversions

时间:2014-07-17 00:24:27      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   strong   io   for   

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

标签:style   blog   color   strong   io   for   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!