二维线段树
Posted 一只特立独行的猫
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二维线段树相关的知识,希望对你有一定的参考价值。
线段树在用于一维空间中进行单点修改和区间查询非常具有优势,同样,在二维空间中线段树也可以实现该功能。可以查询区间和或者最小值。在面临多次单点修改和区间查询时,还是非常具有优势。如果需要进行区间修改和区间查询,那么就引入lazytag标记就可以实现优化。
对比一下一维和二维线段树划分区间的思路:
一维线段树划分区间思路:
二维线段树划分区间的思路:
大概就是上述思路,然后我们来看代码:
#include<iostream>
#define _1 node<<2 //第一象限
#define _2 node<<2|1 //第二象限
#define _3 node<<2|2 //第三象限
#define _4 node<<2|3 //第四象限
#define midx ((left + right) >> 1)
#define midy ((down + up) >> 1)
typedef long long ll;
using namespace std;
const int N = 3e2 + 5;
ll a[N][N],tree[(N<<4)*(N<<4)];
void treeUp(int node, int left, int right, int up, int down) {
//向上更新
//传入区间变量为了方便加lazytag
tree[node] = tree[_1] + tree[_2] + tree[_3] + tree[_4];
return;
}
void build(int node,int left,int right,int up,int down) {
if (left > right || up > down) {
return;
}
if (left == right && up == down) {
//定位到一个格子上
tree[node] = a[left][up];
//cout << left << " " << up << " "<<tree[node]<<endl;
return;
}
//cout << left << " " << right << " " << up << " " << down << endl;
build(_1, midx + 1, right, up, midy);
build(_2, left, midx, up, midy);
build(_3, left, midx, midy + 1, down);
build(_4, midx + 1, right, midy + 1, down);
treeUp(node, left, right, up, down);
return;
}
void updata(int node, int left, int right, int up, int down, int x, int y, int val) {
//将x,y处的值更新为val
if (x > right || x<left || y<up || y > down) {
return;
}
if (left == right && up == down) {
a[x][y] = val;
tree[node] = val;
return;
}
updata(_1, midx + 1, right, up, midy, x, y, val);
updata(_2, left, midx, up, midy, x, y, val);
updata(_3, left, midx, midy + 1, down, x, y, val);
updata(_4, midx + 1, right, midy + 1, down, x, y, val);
treeUp(node, left, right, up, down);
}
ll query(int node, int left, int right, int up, int down, int L, int R, int U, int D) {
//查询LRUD围成的矩形的和
if (L > right || R<left || D<up || U > down) {
return 0;
}
if (left>=L&&R>=right&&up>=U&&down<=D) {
return tree[node];
}
ll sum1 = query(_1, midx + 1, right, up, midy, L, R, U, D);
ll sum2 = query(_2, left, midx, up, midy, L, R, U, D);
ll sum3 = query(_3, left, midx, midy + 1, down, L, R, U, D);
ll sum4 = query(_4, midx + 1, right, midy + 1, down, L, R, U, D);
return sum1 + sum2 + sum3 + sum4;
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
build(1, 1, m, 1, n);
int k;
cin >> k;
while (k--) {
int flag;
cin >> flag;
if (flag&1) {
//更新操作
int x, y, c;
cin >> x >> y >> c;
updata(1, 1, m, 1, n, x, y, c);
}
else {
//查询操作
int cnt = 0;
int L, R, U, D;
cin >> L >> R >> U >> D;
cout << query(1, 1, m, 1, n, L,R,U,D) << endl;
}
}
return 0;
}
以上是关于二维线段树的主要内容,如果未能解决你的问题,请参考以下文章