本题可以使用二维异或差分(可能仅限洛谷,下面细讲)。
题目实现
首先我们需要定义数组并存储,但二维数组开肯定会爆,但是 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 ++;//记录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();
}声明:
这是本人的第一篇题解,能力有限,请多多指教。