bzoj 2683: 简单题 (CDQ分治+树状数组)

题目描述

传送门

题目大意
bzoj 2683: 简单题 (CDQ分治+树状数组)_第1张图片

题解

CDQ分治,把询问拆成x1-1,和x2两种操作。
每次将区间中的操作按照横坐标排序,然后二分,加入[l,mid]中的操作,[mid+1,r]中的询问统计[y1,y2]之间的和。

代码

#include
#include
#include
#include
#include
#define N 500003
using namespace std;
int tr[N],n,m,ans[N],mark[N];
struct data{
    int x,y,y1,val,id,mark,opt,b;
}a[N];
int cmp(data a,data b)
{
    return a.xint cmp1(data a,data b)
{
    return a.idint lowbit(int x){
    return x&(-x);
}
int query(int x)
{
    int ans=0;
    for (int i=x;i>=1;i-=lowbit(i)) ans+=tr[i];
    return ans;
}
void change(int x,int val)
{
    for (int i=x;i<=n;i+=lowbit(i))
     tr[i]+=val;
}
void clear(int x)
{
    for (int i=x;i<=n;i+=lowbit(i))
     tr[i]=0;
}
void divide(int l,int r)
{
    if (l==r) return;
    int mid=(l+r)/2;
    for (int i=l;i<=mid;i++) a[i].b=1;
    for (int i=mid+1;i<=r;i++) a[i].b=0;
    sort(a+l,a+r+1,cmp);
    for (int i=l;i<=r;i++) 
     if (a[i].b==1){
        if (a[i].opt==1) change(a[i].y,a[i].val);
    }
    else 
     if (a[i].opt==2) ans[a[i].id]+=a[i].mark*(query(a[i].y1)-query(a[i].y));
    for (int i=l;i<=r;i++) 
     if (a[i].b==1&&a[i].opt==1) clear(a[i].y);
    sort(a+l,a+r+1,cmp1);
    divide(l,mid);
    divide(mid+1,r);
}
int main()
{
    freopen("a.in","r",stdin);
    freopen("my.out","w",stdout);
    scanf("%d",&n); int i=0; int cnt=0;
    while (true) {
        int opt; scanf("%d",&opt);
        if (opt==3) break;
        i++; cnt++;
        a[i].opt=opt; a[i].id=cnt;
        if (opt==1) scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].val);
        else {
            mark[cnt]=1;
            int x,y,x1,y1; scanf("%d%d%d%d",&x,&y,&x1,&y1);
            a[i].id=cnt; a[i].mark=-1; a[i].x=x-1; a[i].y=y-1; a[i].y1=y1;
            ++i;
            a[i].opt=a[i-1].opt; a[i].id=cnt; a[i].mark=1; a[i].x=x1; a[i].y=y-1; a[i].y1=y1;
        }
    }
    divide(1,i);
    for (int j=1;j<=i;j++)
     if (mark[j]) printf("%d\n",ans[j]);
}

你可能感兴趣的:(树状数组,cdq分治&整体二分)