码迷,mamicode.com
首页 > 编程语言 > 详细

SGU180:Inversions(树状数组)

时间:2017-07-26 22:00:23      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:man   stdio.h   sizeof   oid   exp   bsp   family   class   iostream   

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

5 2 3 1 5 4
Output

3


题意:
求逆序数

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <math.h>
#include <bitset>
#include <list>
#include <algorithm>
#include <climits>
using namespace std;

#define lson 2*i
#define rson 2*i+1
#define LS l,mid,lson
#define RS mid+1,r,rson
#define UP(i,x,y) for(i=x;i<=y;i++)
#define DOWN(i,x,y) for(i=x;i>=y;i--)
#define MEM(a,x) memset(a,x,sizeof(a))
#define W(a) while(a)
#define gcd(a,b) __gcd(a,b)
#define LL long long
#define N 67000
#define INF 0x3f3f3f3f
#define EXP 1e-8
#define lowbit(x) (x&-x)
const int mod = 1e9+7;

LL c[N],n,tot,r[N];

struct node
{
    LL x,s,id;
} a[N];

int cmp(node a,node b)
{
    if(a.x!=b.x)
        return a.x<b.x;
    return a.id<b.id;
}

LL sum(LL x)
{
    LL ret = 0;
    while(x>0)
    {
        ret+=c[x];
        x-=lowbit(x);
    }
    return ret;
}

void add(LL x,LL d)
{
    while(x<=n)
    {
        c[x]+=d;
        x+=lowbit(x);
    }
}

int main()
{
    LL i,j,k;
    while(~scanf("%lld",&n))
    {
        MEM(c,0);
        for(i = 1; i<=n; i++)
        {
            scanf("%lld",&a[i].x);
            a[i].id = i;
        }
        sort(a+1,a+1+n,cmp);
        for(i = 1; i<=n; i++)
        {
            r[a[i].id] = i;
        }
        LL ans = 0;
        for(i = 1; i<=n; i++)
        {
            add(r[i],1);
            ans+=(i-sum(r[i]));
        }
        printf("%lld\n",ans);
    }
    return 0;
}


SGU180:Inversions(树状数组)

标签:man   stdio.h   sizeof   oid   exp   bsp   family   class   iostream   

原文地址:http://www.cnblogs.com/claireyuancy/p/7241707.html

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