题意简述
有一个 的方格,初始全白。你要执行以下操作:
- 将第 行涂成黑色。
- 将第 列涂成白色。
每次涂色后请输出当前黑色格子的数量。
思路
记录第 行(或列)最后被涂色的时间戳(即操作时间)(或 )。对于格子 ,它是黑色等价于它被涂黑的时间大于它被涂白的时间,即 。初始由于全白,可以令 ,,初始时间戳为 。
我们按顺序处理修改时动态维护答案。对于操作 ,第 行原本有 个黑格,答案增加 ,并将 修改为当前时间戳;对于操作 ,第 列原本有 个白格,答案减少 ,并将 修改为当前时间戳。修改完毕后时间戳加 。
我们可以使用树状数组维护值为 的 数量,即 。修改时将原值的位置减一,新值的位置加一即可,查询 时只需要在树状数组上查询 的和。对于 同理。时间复杂度 。
代码
#include <bits/stdc++.h>
using namespace std;
int n, q;
struct Fenwick {
int tree[300007];
inline int lowbit(int x) { return x & -x; }
inline void update(int x, int d) {
while (x <= q + 2) {
tree[x] += d;
x += lowbit(x);
}
}
inline int query(int x) {
int ans = 0;
while (x) {
ans += tree[x];
x -= lowbit(x);
}
return ans;
}
inline int range_query(int l, int r) {
if (l > r)
return 0;
else
return query(r) - query(l - 1);
}
} tr, tc;
int op, x;
int rl[300007];
int cl[300007];
long long ans = 0; // 不开 long long 见祖宗
signed main() {
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
cin >> n >> q;
tr.update(1, n);
tc.update(2, n);
fill(rl + 1, rl + n + 1, 1);
fill(cl + 1, cl + n + 1, 2);
for (int i = 3; i <= q + 2; i++) { // 当前时间戳
cin >> op >> x;
if (op == 1) {
ans += n - tc.range_query(1, rl[x] - 1);
tr.update(rl[x], -1);
rl[x] = i;
tr.update(i, 1);
} else if (op == 2) {
ans -= n - tr.range_query(1, cl[x] - 1);
tc.update(cl[x], -1);
cl[x] = i;
tc.update(i, 1);
}
cout << ans << '\n';
}
}