发现当某行 确定时,与其存在约束的其他行方案确定,考虑并查集,将每行拆成反转与不反转两点连边。
思考如何建边,考虑 记录正序状态下上一个在 位产生约束的 。
设行数组 ,并查集 。
- 若存在 且 连接 。
- 若存在 且 连接 。
我们解决了相邻的存在约束的行,但还不够,如:
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';
}
}