bzoj3333 排队计划(线段树)

题目链接

分析:
对于在 p 之前的位置,与其产生的逆序对个数是不会改变的
而在p之后没有被选出的数,与其产生的逆序对个数也不会改变
被选出的数,ta们之间的逆序对经过排序后就都消除了
减少的逆序对个数:每个被选出的数字之后比ta小的数的个数

建立一个线段树,每个结点记录原序列该位置上的数
同时统计ta和后面的数形成的逆序对个数(在ta后面比ta小的数的个数)

每次询问,我们从 pn 中不断找到最小值,减去在ta之后且比ta小的数的个数
因为把这些元素排过序后就不会与之后的数形成逆序对了
所以我们直接把这个位置赋值成INF即可

tip

开ll

逆序对最多有 n(n1)2 个,已经超过了int的范围

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long

using namespace std;

const int INF=1e9;
const int N=500010;
int c[N],n,nn,m,a[N],V[N],MN,ID;
ll sum[N],ans=0;
struct node{
    int mn,id;
};
node t[N<<2];

void add(int x) {for (int i=x;i<=nn;i+=(i&(-i))) c[i]++;}
ll ask(int x) {ll ans=0;for (int i=x;i>0;i-=(i&(-i))) ans+=(ll)c[i];return ans;}

void update(int bh)
{
    int lc=bh<<1;
    int rc=bh<<1|1;
    if (t[lc].mn<t[rc].mn) t[bh].mn=t[lc].mn,t[bh].id=t[lc].id;
    else t[bh].mn=t[rc].mn,t[bh].id=t[rc].id;
}

void build(int bh,int l,int r)
{
    t[bh].mn=INF;
    if (l==r)
    {
        t[bh].id=l; t[bh].mn=a[l];
        return;
    }
    int mid=(l+r)>>1;
    build(bh<<1,l,mid);
    build(bh<<1|1,mid+1,r);
    update(bh);
}

void ask(int bh,int l,int r,int x,int y)
{
    if (l>=x&&r<=y)
    {
        if (t[bh].mn<MN) MN=t[bh].mn,ID=t[bh].id;
        return;
    }
    int mid=(l+r)>>1;
    if (x<=mid) ask(bh<<1,l,mid,x,y);
    if (y>mid) ask(bh<<1|1,mid+1,r,x,y);
}

void change(int bh,int l,int r,int x)
{
    if (l==r)
    {
        t[bh].mn=INF; t[bh].id=0;
        return;
    }
    int mid=(l+r)>>1;
    if (x<=mid) change(bh<<1,l,mid,x);
    else change(bh<<1|1,mid+1,r,x);
    update(bh);
}

int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++) 
        scanf("%d",&a[i]),V[i]=a[i];
    sort(V+1,V+1+n);
    nn=unique(V+1,V+1+n)-V-1;
    for (int i=n;i>=1;i--)
    {
        int x=lower_bound(V+1,V+1+nn,a[i])-V;
        add(x);
        sum[i]=(ll)ask(x-1); ans+=(ll)sum[i];
        a[i]=x;
    }

    printf("%lld\n",ans);
    build(1,1,n);

    for (int i=1;i<=m;i++)
    {
        int x;
        scanf("%d",&x);
        MN=INF,ID=0;
        ask(1,1,n,x,n);
        while (MN<=a[x])
        {
            ans-=(ll)sum[ID];
            sum[ID]=0;
            change(1,1,n,ID);
            MN=INF,ID=0;    
            ask(1,1,n,x,n);
        }
        printf("%lld\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值