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

【bzoj3295】动态逆序对 分块+树状数组

时间:2017-02-23 13:54:07      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:update   typedef   views   bit   number   lock   ons   read   space   

题目描述

给定一个1~n的序列,然后m次删除元素,每次删除之前询问逆序对的个数。

代码

#include <cstdio>
#include <cctype>
#include <cmath>
#include <algorithm>
using namespace std;

typedef long long lint;

const int N=100010;
const int BLOCK_SIZE=1000;
const int BLOCK_NUM=101;

int n,m;

int a[N];
int loc[N];

lint t[N];
lint res;

int num;
lint tr[BLOCK_NUM][N];

inline int read(void)
{
    int x=0; char c=getchar();
    for (;!isdigit(c);c=getchar());
    for (;isdigit(c);c=getchar()) x=x*10+c-‘0‘;
    return x;
}

inline int lowbit(int i)
{
    return i&-i;
}

inline void ins(lint *ta,int i,int add)
{
    for (;i<=n;i+=lowbit(i)) ta[i]+=add;
}

inline lint query(lint *ta,int i)
{
    lint sum=0;
    for (;i;i-=lowbit(i)) sum+=ta[i];
    return sum;
}

inline void update(int x)
{
    int loca=loc[x],bel=(loca-1)/BLOCK_SIZE+1;

    for (int i=BLOCK_SIZE*(bel-1)+1;i<loca;i++)
        if (a[i]>0&&a[i]>x) res--;
    for (int i=loca+1;i<=min(BLOCK_SIZE*bel,n);i++)
        if (a[i]>0&&a[i]<x) res--;

    lint tmp;
    for (int i=1;i<bel;i++)
    {
        tmp=query(tr[i],n)-query(tr[i],x-1);
        res-=tmp;
    }
    for (int i=bel+1;i<=num;i++)
    {
        tmp=query(tr[i],x-1);
        res-=tmp;
    }

    a[loca]=0;
    ins(tr[bel],x,-1);
}

int main(void)
{
//  freopen("a.in","r",stdin);
//  freopen("a.out","w",stdout);

    n=read(),m=read();

    for (int i=1;i<=n;i++) a[i]=read();
    for (int i=1;i<=n;i++) loc[a[i]]=i;

    lint tmp;
    for (int i=n;i>=1;i--)
    {
        tmp=query(t,a[i]);
        res=res+tmp;
        ins(t,a[i],1);
    }

    int belo;
    num=(n-1)/BLOCK_SIZE+1;
    for (int i=1;i<=n;i++)
    {
        belo=(i-1)/BLOCK_SIZE+1;
        ins(tr[belo],a[i],1);
    }

    for (int i=1;i<=m;i++)
    {
        printf("%lld\n",res);
        update(read());
    }

    return 0;
}

【bzoj3295】动态逆序对 分块+树状数组

标签:update   typedef   views   bit   number   lock   ons   read   space   

原文地址:http://www.cnblogs.com/Sdchr/p/6111274.html

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