Codeforces Round #368 (Div. 2) D. Persistent Bookcase 主席树套bitset

原题链接:https://codeforces.ml/contest/707/problem/D

题意

有一个二维01矩阵,接下来有四种操作

  1. i j 将第i行第j列的数字置1
  2. i j 将第i行第j列的数字置0
  3. i 将第i行的数字翻转
  4. k 回到第k次操作之后

分析

看到回溯操作,主席树基本就八九不离十了。然后考虑怎么处理每行的信息。

01字符变换,可以用bitset高效处理。对于主席树的每个叶子节点我们开一个bitset容器,对于123操作都可以轻松搞定,然后是计算1的个数。直接用count函数统计可能会多算一些范围之外的值,因此要减去。

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const int N = 100010 + 10;
const int MOD = 1e9 + 7;
int n, m;
struct node {
    int ls, rs, sum;
    bitset<1005> bit;
}hjt[N * 21];
int tot, rt[N];
void modify(int &now, int pre, int pos, int y, int l, int r, int opt) {
    now = ++tot;
    hjt[now] = hjt[pre];
    if (l == r) {
        if (opt == 1) hjt[now].bit.set(y);
        else if (opt == 2) hjt[now].bit.reset(y);
        else if (opt == 3) hjt[now].bit.flip();
        int flag = hjt[now].bit.test(1004);
        hjt[now].sum = hjt[now].bit.count() - flag * (1005 - m);
        return;
    }
    int mid = (l + r) >> 1;
    if (pos <= mid) modify(hjt[now].ls, hjt[pre].ls, pos, y, l, mid, opt);
    else modify(hjt[now].rs, hjt[pre].rs, pos, y, mid+1, r, opt);
    hjt[now].sum = hjt[hjt[now].ls].sum + hjt[hjt[now].rs].sum;
}
void solve () {
    int q; cin >> n >> m >> q;
    for (int i = 1; i <= q; i++) {
        int opt, x, y; cin >> opt;
        if (opt == 1) {
            cin >> x >> y;
            modify(rt[i], rt[i-1], x, y, 1, n, 1);
        } else if (opt == 2) {
            cin >> x >> y;
            modify(rt[i], rt[i-1], x, y, 1, n, 2);
        } else if (opt == 3) {
            cin >> x;
            modify(rt[i], rt[i-1], x, y, 1, n, 3);
        } else {
            cin >> x;
            rt[i] = rt[x];
        }
        cout << hjt[rt[i]].sum << endl;
    }
}
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#ifdef ACM_LOCAL
    freopen("input", "r", stdin);
    freopen("output", "w", stdout);
#endif
    solve();
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值