cdq实现树状数组

题目链接

思路

毒瘤的一批的东西

也算是cdq的一个应用吧

代码

#include<bits/stdc++.h>
#define fi first
#define se second
#define debug cout<<"I AM HERE"<<endl;
using namespace std;
typedef long long ll;
const int maxn=2e6+5,inf=0x3f3f3f3f,mod=1e9+7;
const double eps=1e-6;
int n,m,cnt;
struct node{
    int opt,x,y;
}a[maxn],b[maxn];
int ans[maxn];

void cdq(int l,int r){
    if(l>=r){
        return ;
    }
    int mid=(l+r)/2,sum=0;
    cdq(l,mid);
    cdq(mid+1,r);
    int pos1=l,pos2=mid+1,id=l;
    while(pos1<=mid&&pos2<=r){
        if(a[pos1].x<=a[pos2].x){
            if(a[pos1].opt==1) sum+=a[pos1].y;
            b[id++]=a[pos1++];
        }else{
            if(a[pos2].opt==2) ans[a[pos2].y]-=sum;
            if(a[pos2].opt==3) ans[a[pos2].y]+=sum;
            b[id++]=a[pos2++];
        }
    }
    while(pos1<=mid) b[id++]=a[pos1++];
    while(pos2<=r){
        if(a[pos2].opt==2) ans[a[pos2].y]-=sum;
        if(a[pos2].opt==3) ans[a[pos2].y]+=sum;
        b[id++]=a[pos2++];
    }
    for(int i=l;i<=r;i++){
        a[i]=b[i];
    }
}

signed main(){
    scanf("%d%d",&n,&m);
    for(int i=1,x;i<=n;i++){
        scanf("%d",&x);
        a[++cnt]={1,i,x};
    }
    int tot=0;
    for(int i=1,opt,x,y;i<=m;i++){
        scanf("%d%d%d",&opt,&x,&y);
        if(opt==1){
            a[++cnt]={1,x,y};
        }else{
            ++tot;
            a[++cnt]={2,x-1,tot};
            a[++cnt]={3,y,tot};
        }
    }
    cdq(1,cnt);
    for(int i=1;i<=tot;i++){
        printf("%d\n",ans[i]);
    }
    return 0;
}


posted @ 2021-09-16 19:44  hunxuewangzi  阅读(34)  评论(0编辑  收藏  举报