bzoj 1176 Mokia (cdq分治)

1176: [Balkan2007]Mokia

Time Limit: 30 Sec  Memory Limit: 162 MB
Submit: 3874  Solved: 1742
[Submit][Status][Discuss]

Description

维护一个W*W的矩阵,初始值均为S.每次操作可以增加某格子的权值,或询问某子矩阵的总权值.修改操作数M<=160000,询问数Q<=10000,W<=2000000.

Input

第一行两个整数,S,W;其中S为矩阵初始值;W为矩阵大小

接下来每行为一下三种输入之一(不包含引号):

"1 x y a"

"2 x1 y1 x2 y2"

"3"

输入1:你需要把(x,y)(第x行第y列)的格子权值增加a

输入2:你需要求出以左下角为(x1,y1),右上角为(x2,y2)的矩阵内所有格子的权值和,并输出

输入3:表示输入结束

Output

对于每个输入2,输出一行,即输入2的答案

Sample Input

0 4
1 2 3 3
2 1 1 3 3
1 2 2 2
2 2 2 3 4
3

Sample Output

3
5

HINT

保证答案不会超过int范围

解题思路:由于矩形很大,无法用二维树状数组解决,,所以转化为三维偏序问题。

时间,x,y

对于一个查询,分成两个前缀的查询。

对于一个查询,我们需要统计的是x小于等于它,y在他的y之间的和。

可以对时间分治,也可以对x分治。

ps:建议不要在分治的过程中套用sort,我们可以仿照归并排序的方式,在统计的时候对x进行归并,就能保证左边和右边的x是有序的。

#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define sca(x) scanf("%d",&x)
#define N 2000005
#define lowb(x) (x&(-x))

struct node
{
    int op,x,y,x1,y1,id;
}a[N],b[N];

struct BIT
{
    int c[N];
    void add(int x,int val)
    {
        for(int i=x; i<=N; i+=lowb(i))c[i]+=val;
    }

    int  ask(int x)
    {
        int ans=0;
        for(int i=x; i; i-=lowb(i))ans+=c[i];
        return ans;
    }
} bit;

int ou[N];

bool cmp(node a,node b)
{
    return a.x<b.x;
}

void cdq(int l,int r)
{
    if(l==r) return ;
    int m=(l+r)>>1;
    cdq(l,m);
    cdq(m+1,r);

    int L=l,R=m+1;
    int tmp=L;
    for(; R<=r; R++)
    {
        while(L<=m&&a[L].x<=a[R].x)
        {
            if(a[L].op==1)bit.add(a[L].y,a[L].x1);
            b[tmp++]=a[L++];
        }
        b[tmp++]=a[R];
        if(a[R].op==2)
        {
            ou[a[R].id]-=bit.ask(a[R].y1)-bit.ask(a[R].y-1);
        }
        else if(a[R].op==3)
        {
            ou[a[R].id]+=bit.ask(a[R].y1)-bit.ask(a[R].y-1);
        }
    }
    for(int i=l; i<L; i++)if(a[i].op==1)bit.add(a[i].y,-a[i].x1);
    while(L<=m)b[tmp++]=a[L++];
    while(R<=r)b[tmp++]=a[R++];
    for(int i=l;i<=r;i++)a[i]=b[i];
}

int main()
{
    int s,w;
    cin>>s>>w;
    int cnt=1;
    int qid=1;
    int op;
    while(1)
    {
        scanf("%d",&op);
        if(op==1)
        {
            a[cnt].op=1;
            sca(a[cnt].x);
            sca(a[cnt].y);
            sca(a[cnt].x1);
            cnt++;
        }
        else if(op==2)
        {
            a[cnt].op=2;
            int x,y,x1,y1;
            sca(x),sca(y),sca(x1),sca(y1);
            a[cnt].x=x-1,a[cnt].y=y,a[cnt].y1=y1,a[cnt].id=qid;
            cnt++;
            a[cnt].op=3;
            a[cnt].x=x1,a[cnt].y=y,a[cnt].y1=y1,a[cnt].id=qid;
            cnt++;
            qid++;
        }
        else break;
    }
    cdq(1,cnt-1);
    for(int i=1;i<qid;i++){
        printf("%d\n",ou[i]);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40894017/article/details/89021429
今日推荐