题目大意

给你一个 $n \times m$ 的网格,初始时,每个网格都是墙。现在你会对这个网格实施 $q$ 次爆破,对于第 $i$ 次爆破,有如下两种情况:

  1. 如果爆破点 $(x, y)$ 是一堵墙,那么就将这个墙炸掉

  2. 如果爆破点不是一堵墙,那么就将这个格子的上、下、左、右的第一堵墙炸掉

你需要求解出经过这 $q$ 次爆破后,现在这个网格下还剩多少面墙没有被炸掉。

解题思路

如果我们直接枚举上、下、左、右的第一堵,那么肯定是不现实的,因为 $n \times m = 4 \times 10^5$,直接 T 飞。

那我们如何做呢?

我们发现这个枚举就是枚举的行和列,那我们能否就只记录行和列呢?答案是可以的。

我们可以用 set 记录每一行每一列的信息,然后用 set 中的函数 lower_bound 这个东西来查找一个位置是否存在,然后用 set 中的 erase 函数删除。

需要注意的是,如果行将一个位置删除了,记得列也要删除。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <bits/stdc++.h>

using namespace std;

const int N = 4e5 + 10;

int n, m, q, ans;
set<int> xx[N], yy[N];

int main() {
cin >> n >> m >> q;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
xx[i].insert(j), yy[j].insert(i);
while (q--) {
int x, y;
cin >> x >> y;
if (xx[x].find(y) != xx[x].end()) {
xx[x].erase(y);
yy[y].erase(x);
} else {
vector<int> v;
auto i = xx[x].lower_bound(y);
if (i != xx[x].end()) v.push_back(*i);
if (i != xx[x].begin()) v.push_back(*(--i));
for (auto t : v) xx[x].erase(t), yy[t].erase(x);
v.clear();
i = yy[y].lower_bound(x);
if (i != yy[y].end()) v.push_back(*i);
if (i != yy[y].begin()) v.push_back(*(--i));
for (auto t : v) yy[y].erase(t), xx[t].erase(y);
}
}
for (int i = 1; i <= n; i++)
ans += xx[i].size();
cout << ans;
return 0;
}