跳到正文

题解

题解:P17182 [ICPC 2017 Hong Kong R] Black and White

I_can_AC约 4 分钟
原文

这是 2026年8月3日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年8月3日
收录
2026年8月3日
更新
2026年11月13日
篇幅
约 4 分钟
题目
P17182

版本

  1. v4当前
  2. v3
  3. v2
  4. v1

本题可以使用二维异或差分(可能仅限洛谷,下面细讲)。

题目实现

首先我们需要定义数组并存储,但二维数组开肯定会爆,但是bool类型可以降低一点,并且主体用异或,所以理论上会爆,但实测没有。

首先,我们先输入 x1x1 y1y1 x2x2 y2y2,这个是区间,然后用差分原理,异或区间,使00变成11,11变成00.

然后全部遍历一遍,记录11的次数,用ansans记录。

最后输出ansans,把数组清零。

剩下一些边角料(多测等),就不过多阐述了。

AC代码

C++
#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();
	
}

这里附上扫面线+线段树代码:

C++
#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';
	}
}

声明:

这是本人的第一篇题解,能力有限,请多多指教