树状树状逆序对数模版

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
const int MAXSIZE = 100100;
 int b[MAXSIZE];
int n,tree[MAXSIZE];
void add(int k,int num)
{
    while(k<=n)
    {
        tree[k]+=num;
        k+=k&-k;
    }
}

int read(int k)
{
    int sum=0;
    while(k)
    {
        sum+=tree[k];
        k-=k&-k;
    }
    return sum;
}
struct node
{
    int val,pos;
}a[MAXSIZE];
bool cmp(node a,node b)
{
    return a.val < b.val;
}
int main(void)
{
    int i,j,x,y;

    while(~scanf("%d",&n))
    {
        memset(tree,0,sizeof(tree));
        for(i=1;i<=n;i++)
        {
            scanf("%d",&a[i].val);
            a[i].pos = i;
        }
        sort(a+1,a+1+n,cmp);
        int cnt = 1;
        for(i=1;i<=n;i++)
        {
            if(i != 1 && a[i].val != a[i-1].val)
                cnt++;
            b[a[i].pos] = cnt;
        }
        LL sum = 0;
        for(i=1;i<=n;i++)
        {
            add(b[i],1);
            sum += (i - read(b[i]));
        }

        printf("%lld\n",sum);
    }

    return 0;
}
View Code

学习应用可参考本博客 线段树分类处

posted @ 2019-01-17 11:12  shuai_hui  阅读(135)  评论(0编辑  收藏  举报