传送门
题目描述
维护一个二维零一矩阵(n,m<=1000),支持四种操作(不超过10^5次):
将(i,j)置一
将(i,j)置零
将第i行零一反转
回到第K次操作前的状态
每次操作后输出全局一共有多少个一
分析
涉及到版本问题,很自然就想到了可持久化数据结构了
很明显这题可以去建主席树维护,但是怎么建树,怎么去维护,就是一个很头疼的问题了
因为这里有一个强制性翻转,所以我们不可以去用标记永久化的操作进行区间修改
我们可以把每一行当作一个元素,然后建一个1 - n长度的线段,用主席树去维护,至于怎么把行当作元素处理呢,可以用bitset来进行处理,这样这个问题就变得很容易解决了
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#include <bitset>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 1e3 + 10;
bitset <N> nums;
struct Node{
int l,r,sum;
bitset <N> a;
}tr[N * N * 2];
int root[N * N];
int ppp;
int n,m,q,idx,now;
int insert(int p,int l,int r,int op,int x,int y){
int q = ++idx;
tr[q] = tr[p];
if(l == r){
if(op == 1){
tr[q].a.set(y);
}
else if(op == 0){
tr[q].a.reset(y);
}
else{
for(int i = 1;i <= m;i++) tr[q].a[i].flip();
}
tr[q].sum = tr[q].a.count();
return q;
}
int mid = l + r >> 1;
if(x <= mid) tr[q].l = insert(tr[p].l,l,mid,op,x,y);
else tr[q].r = insert(tr[p].r,mid + 1,r,op,x,y);
tr[q].sum = tr[tr[q].l].sum + tr[tr[q].r].sum;
return q;
}
int main(){
scanf("%d%d%d",&n,&m,&q);
for(int i = 1;i <= m;i++) nums.set(i);
while(q--){
int op,x,y;
now++;
scanf("%d%d",&op,&x);
if(op == 1){
scanf("%d",&y);
root[now] = insert(root[now - 1],1,n,1,x,y);
}
else if(op == 2){
scanf("%d",&y);
root[now] = insert(root[now - 1],1,n,0,x,y);
}
else if(op == 3){
root[now] = insert(root[now - 1],1,n,-1,x,y);
}
else{
root[now] = root[x];
}
printf("%d\n",tr[root[now]].sum);
}
return 0;
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/