本题可以使用二维异或差分(可能仅限洛谷,下面细讲)。
题目实现
首先我们需要定义数组并存储,但二维数组开肯定会爆,但是bool类型可以降低一点,并且主体用异或,所以理论上会爆,但实测没有。
首先,我们先输入 ,这个是区间,然后用差分原理,异或区间,使变成,变成.
然后全部遍历一遍,记录的次数,用记录。
最后输出,把数组清零。
剩下一些边角料(多测等),就不过多阐述了。
AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 2;
int n, k;
bool a[maxn][maxn];
void solve(){
cin >> n >> k;
while(k --){
int x1, y1, x2, y2;
cin >> x1 >> x2 >> y1 >> y2;
a[x1][y1] ^= 1;
a[x1][y2 + 1] ^= 1;
a[x2 + 1][y1] ^= 1;
a[x2 + 1][y2 + 1] ^= 1;
}
long long ans = 0;
for(int i = 1; i <= n; i ++){
for(int j = 1; j <= n; j ++){
a[i][j] ^= a[i - 1][j] ^ a[i][j - 1] ^ a[i - 1][j - 1];
if(a[i][j] == 1) ans ++;
}
}
cout << ans << endl;
for(int i = 1; i <= n + 1; i ++){
for(int j = 1;j <= n + 1;j ++){
a[i][j] = 0;
}
}
}
int main(){
int t;
cin >> t;
while(t --) solve();
}这里附上扫面线+线段树代码:
#include<bits/stdc++.h>
#define N 10005
using namespace std;
int t,n,k,c,i,xl,xr,yl,yr;
vector<pair<int,int> >v[N];
struct SGT{
int l[N<<2],r[N<<2],s0[N<<2],s1[N<<2],g[N<<2];
void build(int x,int y,int p){
l[p]=x;
r[p]=y;
s0[p]=y-x+1;
s1[p]=g[p]=0;
if(x==y)return;
build(x,(x+y)/2,p<<1);
build((x+y)/2+1,y,p<<1|1);
}
void down(int p){
if(g[p]){
swap(s0[p<<1],s1[p<<1]);
swap(s0[p<<1|1],s1[p<<1|1]);
g[p<<1]^=1;
g[p<<1|1]^=1;
}
g[p]=0;
}
void modify(int x,int y,int p){
if(l[p]>y||r[p]<x)return;
if(l[p]>=x&&r[p]<=y){
swap(s0[p],s1[p]);
g[p]^=1;
return;
}
down(p);
modify(x,y,p<<1);
modify(x,y,p<<1|1);
s0[p]=s0[p<<1]+s0[p<<1|1];
s1[p]=s1[p<<1]+s1[p<<1|1];
}
}sgt;
int main(){
cin.tie(0)->sync_with_stdio(0);
cin>>t;
while(t--){
cin>>n>>k;
sgt.build(1,n,1);
while(k--){
cin>>xl>>xr>>yl>>yr;
v[xl].emplace_back(yl,yr);
v[xr+1].emplace_back(yl,yr);
}
c=0;
for(i=1;i<n+2;i++){
for(auto j:v[i])sgt.modify(j.first,j.second,1);
c+=sgt.s1[1];
v[i].clear();
}
cout<<c<<'\n';
}
}声明:
这是本人的第一篇题解,能力有限,请多多指教