【ybt金牌导航6-5-3】【luogu P4390】定位系统 / Mokia 摩基亚(CDQ分治)(树状数组)

定位系统 / Mokia 摩基亚

题目链接:ybt金牌导航6-5-3 / luogu P4390

题目大意

给你一个二维矩阵,然后有两种操作。
在一个位置加一个数,或者询问一个子矩阵中所有数的和。

思路

首先看到矩阵数点求想到 CDQ 分治。
然后你把每个询问的矩阵拆开成四个起点是 0 , 0 0,0 0,0 的矩阵,就可以用 CDQ 分治加树状数组解决了。

代码

#include<map>
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

struct node {
	int kd, x, y, a, pl, op, t;
}a[800001];
int op, n, m, x1, x2, y1, y2;
int q, ans[10001], t, aa;

void csh() {
	m = 0; q = 0; t = 0;
}

bool cmp0(node x, node y) {
	if (x.t != y.t) return x.t < y.t;
	if (x.x != y.x) return x.x < y.x;
	return x.y < y.y;
}

bool cmp1(node x, node y) {
	if (x.x != y.x) return x.x < y.x;
	return x.y < y.y;
}

struct szsj {//树状数组
	int a[2000001];
	
	void insert(int x, int p) {
		for (; x <= n; x += x & -x)
			a[x] += p;
	}
	
	int query(int x) {
		int re = 0;
		for (; x; x -= x & -x)
			re += a[x];
		return re;
	}
	
	void clear(int x) {
		for (; x <= n; x += x & -x) a[x] = 0;
	}
}T;

void slove(int l, int r) {
	if (l == r) return ;
	
	int mid = (l + r) >> 1;
	slove(l, mid); slove(mid + 1, r);
	
	sort(a + l, a + mid + 1, cmp1);
	sort(a + mid + 1, a + r + 1, cmp1);
	int i = l, j = mid + 1;
	while (j <= r) {
		while (a[i].x <= a[j].x && i <= mid) {
			if (a[i].kd == 1) T.insert(a[i].y, a[i].a);
			i++;
		}
		if (a[j].kd == 2) ans[a[j].pl] += a[j].op * T.query(a[j].y);
		j++;
	}
	
	for (int i = l; i <= r; i++)
		if (a[i].kd == 1) T.clear(a[i].y);
}

int main() {
	scanf("%d", &op);
	while (op != 3) {
		scanf("%d", &n);
		csh();
		scanf("%d", &op);
		while (op != 0 && op != 3) {
			t++;
			if (op == 1) {
				scanf("%d %d %d", &x1, &y1, &aa);
				a[++m] = (node){1, x1, y1, aa, 0, 0, t};
			}
			else {
				scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
				a[++m] = (node){2, x2, y2, 0, ++q, 1, t};//拆成四个从 0,0 出发的矩阵求解
				a[++m] = (node){2, x1 - 1, y2, 0, q, -1, t};
				a[++m] = (node){2, x2, y1 - 1, 0, q, -1, t};
				a[++m] = (node){2, x1 - 1, y1 - 1, 0, q, 1, t};
			}
			
			scanf("%d", &op);
		}
		
//		sort(a + 1, a + m + 1, cmp0);
		slove(1, m);
		
		for (int i = 1; i <= q; i++) {
			printf("%d\n", ans[i]); ans[i] = 0;
		}
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值