跳到正文

题解

题解:AT_abc449_f [ABC449F] Grid Clipping

kaikai_qwq约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年3月19日
更新
2026年3月19日
篇幅
约 4 分钟

版本

  1. v1当前

前言

本篇题解顺便纪念一下这个彩笔第一次 ABCDEF & AT 上青。

思路

可以发现,对于 HH 行 WW 列的矩阵,其左上角的前 H−h+1H - h + 1,前 W−w+1W - w + 1 列的组成的矩阵(以下将这个矩阵称为 AA),每个点都可以对应一个向右下的 hh 行 ww 列的矩阵。容易发现,可以用 AA 的面积,减去 AA 中点对应的矩阵中包含黑点的点个数,即是答案。

对于一个黑点 (r,c)(r, c),AA 中 r−h+1≤x≤r,c−w+1≤y≤cr - h + 1\le x\le r, c - w + 1\le y\le c 的点 (x,y)(x, y) 对应的矩阵都含有这个黑点,于是,可以将每个黑点转换成一个矩阵。

那么,这些黑点矩阵的面积并,就是 AA 中点对应的矩阵中包含黑点的点个数,用 AA 的面积减去即是答案。

矩阵面积并使用扫描线实现。

代码

C++
//使用线段树实现扫描线
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 1e6 + 10;
int qwq[MAXN * 2], n, ans;
int H, W, h, w;
struct node_line {
	int l, r, h;
	int type;
}line[MAXN * 2];
struct node_tree {
	int l, r;
	int sum, len;
}tree[MAXN * 4];
bool cmp(node_line a, node_line b) {
	return a.h < b.h;
}
void build(int u, int l, int r) {
	tree[u].l = l, tree[u].r = r;
	if (l == r) {
        return;
    }
	int mid = (l + r) / 2;
	build(u * 2, l, mid);
	build(u * 2 + 1, mid + 1, r);
}
void pushup(int u) {
	if (tree[u].sum) {
        tree[u].len = qwq[tree[u].r + 1] - qwq[tree[u].l];
    } else {
        tree[u].len = tree[u * 2].len + tree[u * 2 + 1].len;
    }
}
void update(int u, int L, int R, int w) {
	int l = tree[u].l, r = tree[u].r;
	if (qwq[r + 1] <= L || R <= qwq[l]) {
        return;
    }
	if (L <= qwq[l] && qwq[r + 1] <= R) {
		tree[u].sum += w;
		pushup(u);
		return;
	}
	update(u * 2, L, R, w);
	update(u * 2 + 1, L, R, w);
	pushup(u);
}
signed main() {
	cin >> H >> W >> h >> w;
	cin >> n;
	H = H - h + 1;
	W = W - w + 1;//转换为 A 矩阵
	int res = H * W;
	if (!n) {
		cout << res;
		return 0;
	}
	for (int i = 1; i <= n; i++) {
		int r, c;
		cin >> r >> c;
		int x11, x22, y11, y22;
		x11 = max(1ll, r - h + 1);
		x22 = min(r, H);
		y11 = max(1ll, c - w + 1);
		y22 = min(c, W);//黑点矩阵
		x22++, y22++;//加 1 是因为扫描线处理不了宽度为 0 的情况
		qwq[2 * i - 1] = x11, qwq[2 * i] = x22;
		line[2 * i - 1] = {x11, x22, y11, 1};
		line[2 * i] = {x11, x22, y22, -1};
	}
	sort(line + 1, line + 2 * n + 1, cmp);
	sort(qwq + 1, qwq + 2 * n + 1);
	int t0t = unique(qwq + 1, qwq + 2 * n + 1) - qwq - 1;
	build(1, 1, t0t - 1);
	for (int i = 1; i < 2 * n; i++) {
		update(1, line[i].l, line[i].r, line[i].type);
		ans += tree[1].len * (line[i + 1].h - line[i].h);
	}
	cout << res - ans;
	return 0;
}
原文