2683: 简单题
Time Limit: 50 Sec Memory Limit: 128 MBSubmit: 904 Solved: 371
[ Submit][ Status][ Discuss]
Description
你有一个N*N的棋盘,每个格子内有一个整数,初始时的时候全部为0,现在需要维护两种操作:
命令 | 参数限制 | 内容 |
1 x y A | 1<=x,y<=N,A是正整数 | 将格子x,y里的数字加上A |
2 x1 y1 x2 y2 | 1<=x1<= x2<=N 1<=y1<= y2<=N | 输出x1 y1 x2 y2这个矩形内的数字和 |
3 | 无 | 终止程序 |
Input
输入文件第一行一个正整数N。
接下来每行一个操作。
Output
对于每个2操作,输出一个对应的答案。
Sample Input
4
1 2 3 3
2 1 1 3 3
1 2 2 2
2 2 2 3 4
3
1 2 3 3
2 1 1 3 3
1 2 2 2
2 2 2 3 4
3
Sample Output
3
5
5
HINT
1<=N<=500000,操作数不超过200000个,内存限制20M。
对于100%的数据,操作1中的A不超过2000。
Source
前面的添加操作对后面的询问操作产生影响,上CDQ分治
每个询问拆成4个矩形询问(1,1)到(r,c)的数字和
离散一下列坐标,用树状数组处理前缀和就行了
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 5E5 + 50;
const int maxm = 2E5 + 20;
struct data{int typ,r1,r2,c1,c2;} q[maxm];
struct d2{
int typ,r,c,A,B;
bool operator < (const d2 &b) const {
if (r < b.r) return 1;
if (r > b.r) return 0;
return typ < b.typ;
}
}d[maxm*4];
int n,m,tot,ans[maxm],a[maxm*4],c[maxn];
void Add(int cnt,int N,int r,int c,int A,int B)
{
d[cnt].typ = 2; a[N] = c;
d[cnt].r = r; d[cnt].c = c;
d[cnt].A = A; d[cnt].B = B;
}
void Solve(int L,int R)
{
if (L == R) return;
int mid = (L + R) >> 1;
Solve(L,mid); Solve(mid + 1,R);
int cur = 1,cnt = 0,N = 0;
for (int i = L; i <= mid; i++)
if (q[i].typ == 1) {
++cnt; d[cnt].A = q[i].r2;
d[cnt].typ = 1; a[++N] = d[cnt].c;
d[cnt].r = q[i].r1; d[cnt].c = q[i].c1;
}
for (int i = mid + 1; i <= R; i++)
if (q[i].typ == 2) {
Add(++cnt,++N,q[i].r1-1,q[i].c1-1,i,1);
Add(++cnt,++N,q[i].r1-1,q[i].c2,i,-1);
Add(++cnt,++N,q[i].r2,q[i].c1-1,i,-1);
Add(++cnt,++N,q[i].r2,q[i].c2,i,1);
}
sort(d + 1,d + cnt + 1);
sort(a + 1,a + N + 1);
for (int i = 2; i <= N; i++)
if (a[i] != a[i-1])
a[++cur] = a[i];
for (int i = 1; i <= cur; i++) c[i] = 0;
for (int i = 1; i <= cnt; i++)
if (d[i].typ == 1) {
int pos = d[i].c;
pos = lower_bound(a + 1,a + cur + 1,pos) - a;
for (int j = pos; j <= cur; j += j&-j) c[j] += d[i].A;
}
else {
int pos = d[i].c;
pos = lower_bound(a + 1,a + cur + 1,pos) - a;
int sum = 0;
for (int j = pos; j > 0; j -= j&-j) sum += c[j];
ans[d[i].A] += sum*d[i].B;
}
}
int getint()
{
char ch = getchar();
int ret = 0;
while (ch < '0' || '9' < ch) ch = getchar();
while ('0' <= ch && ch <= '9')
ret = ret*10 + ch - '0',ch = getchar();
return ret;
}
int main()
{
#ifdef DMC
freopen("DMC.txt","r",stdin);
#endif
n = getint();
for (;;) {
int typ = getint();
if (typ == 3) break;
if (typ == 1) {
++tot;
q[tot].typ = typ;
q[tot].r1 = getint();
q[tot].c1 = getint();
q[tot].r2 = getint();
}
else {
++tot;
q[tot].typ = typ;
q[tot].r1 = getint();
q[tot].c1 = getint();
q[tot].r2 = getint();
q[tot].c2 = getint();
}
}
Solve(1,tot);
for (int i = 1; i <= tot; i++)
if (q[i].typ == 2)
printf("%d\n",ans[i]);
return 0;
}