跳到正文

题解

题解:P16314 [ICPC 2023 Jinan R] 来自知识的礼物

Fish_Scale约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年9月10日
收录
2026年9月10日
更新
2026年11月11日
篇幅
约 4 分钟
题目
P16314

版本

  1. v3当前
  2. v2
  3. v1

发现当某行 rr 确定时,与其存在约束的其他行方案确定,考虑并查集,将每行拆成反转与不反转两点连边。

思考如何建边,考虑 headjhead_j 记录正序状态下上一个在 jj 位产生约束的 rr。

设行数组 aia_i,并查集 fi,0/1f_{i,0/1}。

  • 若存在 headjhead_j 且 aj=1a_j=1 连接 (fi,0,fheadj,1),(fi,1,fheadj,0)(f_{i,0},f_{head_j,1}),(f_{i,1},f_{head_j,0})。
  • 若存在 headjhead_j 且 ac−j−1=1a_{c-j-1}=1 连接 (fi,0,fheadj,0),(fi,1,fheadj,1)(f_{i,0},f_{head_j,0}),(f_{i,1},f_{head_j,1})。

我们解决了相邻的存在约束的行,但还不够,如:

代码
10
10
10
ans=0

反转 r=2r=2后满足了相邻的约束,但是非相邻没有。

我们可以再记录 head2jhead2_j 记录正序状态下上上一个在 jj 位产生约束的 rr,以同样方式处理。

为什么只需记录到上上个,因为翻转上个后上上个不能翻转,一定被约束

如果 fi,0,fi,1f_{i,0},f_{i,1} 在同一联通块下为无解,否则答案为 2cnt2^{cnt},cntcnt 为连通块数,将 fi,0,fi,1f_{i,0},f_{i,1} 视为同一连通块,因为两者等价。

C++
#include<bits/stdc++.h>
#define int long long 
#define LOCAL 0
#define ONLINE 1
using namespace std;
const int N=2e6+10,mod=1e9+7;
int r,c,head[N],f[N],cnt[N],T,head2[N];
bool a[N],vis[N];
int find(int x){
	return x==f[x]?x:f[x]=find(f[x]);
}
char ch;
int solve(){
	cin>>r>>c;
	for(int i=0;i<c;i++)cnt[i]=a[i]=0,head2[i]=head[i]=-1;
	for(int i=0;i<r;i++)vis[i]=0;
	for(int i=0;i<r*2;i++)f[i]=i;
	for(int i=0;i<r;i++){
		for(int j=0;j<c;j++)cin>>ch,a[j]=(ch=='1'),cnt[j]+=(ch=='1');
		for(int j=0;j<c;j++){
			if(head[j]!=-1&&a[c-j-1])f[find(i<<1)]=find(head[j]<<1),f[find(i<<1|1)]=find(head[j]<<1|1);
			if(head[j]!=-1&&a[j])f[find(i<<1)]=find(head[j]<<1|1),f[find(i<<1|1)]=find(head[j]<<1);
			if(head2[j]!=-1&&a[c-j-1])f[find(i<<1)]=find(head2[j]<<1),f[find(i<<1|1)]=find(head2[j]<<1|1);
			if(head2[j]!=-1&&a[j])f[find(i<<1)]=find(head2[j]<<1|1),f[find(i<<1|1)]=find(head2[j]<<1);
		}
		for(int j=0;j<c;j++)if(a[j])head2[j]=head[j],head[j]=i;
	}
	//for(int i=0;i<c;i++)cout<<cnt[i]<<' ';cout<<'\n';
	for(int i=0;i<c;i++)if(cnt[i]>2)return 0;
	for(int i=0;i<r;i++)if(find(i<<1)==find(i<<1|1))return 0;
	int ans=1;
	for(int i=0;i<r;i++){
		if(vis[find(i<<1)>>1]||vis[find(i<<1|1)>>1])continue;
		ans=(ans*2)%mod;
		vis[find(i<<1)>>1]=vis[find(i<<1|1)>>1]=1;
	}
	return ans;
}
signed main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	#if LOCAL
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
	#endif
	#if ONLINE
	freopen("reverse.in","r",stdin);
	freopen("reverse.out","w",stdout);
	#endif
	cin>>T;
	while(T--){
		cout<<solve()<<'\n';
	}
} 
原文