题目大意: 维护一个W*W的矩阵,每次操作可以增加某格子的权值,或询问某子矩阵的总权值。
题解:CDQ分治,把询问拆成四个小矩形
卡点:无
C++ Code:
#include <cstdio> #include <algorithm> #define int long long #define lb(x) (x & -x) using namespace std; struct node { int op, id, x, y, num; }q[200010], tmp[200010]; int S, W, op, num, cnt; int T[2000010]; inline bool cmp(node a, node b) {return a.id < b.id;} void add(int p, int num) {for (int i = p; i <= W; i += lb(i)) T[i] += num;} int ask(int p) {int res = 0; for(int i = p; i; i -= lb(i)) res += T[i]; return res;} void clear(int p) {for (int i = p; i <= W; i += lb(i)) T[i] = 0;} void CDQ(int l, int r) { if (l >= r) return ; int mid = l + r >> 1; CDQ(l, mid); CDQ(mid + 1, r); int p1 = l, p2 = mid + 1, p3 = l; while (p1 <= mid && p2 <= r) { if (q[p1].x <= q[p2].x) { if (!q[p1].op) add(q[p1].y, q[p1].num); tmp[p3++] = q[p1++]; } else { if (q[p2].op) q[p2].num += ask(q[p2].y); tmp[p3++] = q[p2++]; } } while (p1 <= mid) { if (!q[p1].op) add(q[p1].y, q[p1].num); tmp[p3++] = q[p1++]; } while (p2 <= r) { if (q[p2].op) q[p2].num += ask(q[p2].y); tmp[p3++] = q[p2++]; } for (int i = l; i <= mid; i++) if (!q[i].op) clear(q[i].y); for (int i = l; i <= r; i++) q[i] = tmp[i]; } signed main() { scanf("%lld%lld", &S, &W); while (scanf("%lld", &op)){ if (op == 3) break; if (op == 1){ int x, y, num; scanf("%lld%lld%lld", &x, &y, &num);cnt++; q[cnt] = (node){0, cnt, x, y, num}; }else { int x1, y1, x2, y2; scanf("%lld%lld%lld%lld", &x1, &y1, &x2, &y2); cnt++; q[cnt] = (node) {1, cnt, x1 - 1, y1 - 1, 0}; cnt++; q[cnt] = (node) {1, cnt, x1 - 1, y2, 0}; cnt++; q[cnt] = (node) {1, cnt, x2, y1 - 1, 0}; cnt++; q[cnt] = (node) {1, cnt, x2, y2, 0}; } } CDQ(1, cnt); sort(q + 1, q + cnt + 1, cmp); for (int i = 1; i <= cnt; i++) if (q[i].op) { printf("%lld ", q[i + 3].num - q[i + 1].num - q[i + 2].num + q[i].num + S * (q[i + 3].y - q[i].y) * (q[i + 3].x - q[i].x)); i += 3; } return 0; }