BZOJ1176:[Balkan2007]Mokia(CDQ分治)

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范围

Solution

三维偏序,时间是一维,$x$是一维,$y$是一维。

把询问拆成四个前缀和的形式。那么$CDQ$过程中对于右半边的一个询问,我们要查询的实际就是左半边$x$和$y$都小于它的修改的和,归并的时候用树状数组维护一下。

Code

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #define N (200009)
 5 using namespace std;
 6 
 7 struct Que{int x,y,opt,v;}Q[N],tmp[N];
 8 int s,w,opt,cnt,q_num,c[N*10],ans[N];
 9 
10 inline int read()
11 {
12     int x=0,w=1; char c=getchar();
13     while (c<'0' || c>'9') {if (c=='-') w=-1; c=getchar();}
14     while (c>='0' && c<='9') x=x*10+c-'0', c=getchar();
15     return x*w;
16 }
17 
18 void Update(int x,int k)
19 {
20     for (; x<=w; x+=(x&-x)) c[x]+=k;
21 }
22 
23 int Query(int x)
24 {
25     int ans=0;
26     for (; x; x-=(x&-x)) ans+=c[x];
27     return ans;
28 }
29 
30 void CDQ(int l,int r)
31 {
32     if (l==r) return;
33     int mid=(l+r)>>1;
34     CDQ(l,mid); CDQ(mid+1,r);
35     int i=l,j=mid+1,k=l-1;
36     while (i<=mid || j<=r)
37         if (j>r || i<=mid && (Q[i].x<Q[j].x || Q[i].x==Q[j].x && Q[i].opt<Q[j].opt))
38         {
39             if (Q[i].opt==1) Update(Q[i].y,Q[i].v);
40             tmp[++k]=Q[i]; ++i;
41         }
42         else
43         {
44             if (Q[j].opt==2)
45             {
46                 if (Q[j].v>0) ans[Q[j].v]+=Query(Q[j].y);
47                 else ans[-Q[j].v]-=Query(Q[j].y);
48             }
49             tmp[++k]=Q[j]; ++j;
50         }
51     for (int i=l; i<=mid; ++i)
52         if (Q[i].opt==1) Update(Q[i].y,-Q[i].v);
53     for (int i=l; i<=r; ++i) Q[i]=tmp[i];
54 }
55 
56 int main()
57 {
58     s=read(); w=read();
59     while ((opt=read())!=3)
60         if (opt==1)
61         {
62             int x=read(),y=read(),a=read();
63             Q[++q_num]=(Que){x,y,1,a};
64         }
65         else
66         {
67             int x=read(),y=read(),a=read(),b=read();
68             ++cnt;
69             Q[++q_num]=(Que){x-1,y-1,2,cnt};
70             Q[++q_num]=(Que){a,b,2,cnt};
71             Q[++q_num]=(Que){x-1,b,2,-cnt};
72             Q[++q_num]=(Que){a,y-1,2,-cnt};
73         }
74     CDQ(1,q_num);
75     for (int i=1; i<=cnt; ++i) printf("%d\n",ans[i]);
76 }
posted @ 2019-03-05 17:34  Refun  阅读(190)  评论(0编辑  收藏  举报