SGU180:Inversions(树状数组)

Posted claireyuancy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SGU180:Inversions(树状数组)相关的知识,希望对你有一定的参考价值。

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(树状数组)的主要内容,如果未能解决你的问题,请参考以下文章

SGU180(树状数组,逆序对,离散)

SGU 108 Self-numbers 2 (另一种滚动数组)

浅析树状数组

SGU101题解

sgu 544

树状数组板子