题解:P16314 [ICPC 2023 Jinan R] 来自知识的礼物
Fish_Scale · · 题解
发现当某行
思考如何建边,考虑
设行数组
- 若存在
head_j 且a_j=1 连接(f_{i,0},f_{head_j,1}),(f_{i,1},f_{head_j,0}) 。 - 若存在
head_j 且a_{c-j-1}=1 连接(f_{i,0},f_{head_j,0}),(f_{i,1},f_{head_j,1}) 。
我们解决了相邻的存在约束的行,但还不够,如:
10
10
10
ans=0
反转
我们可以再记录
为什么只需记录到上上个,因为翻转上个后上上个不能翻转,一定被约束
如果
#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';
}
}