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

· · 题解

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

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

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

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

10
10
10
ans=0

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

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

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

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

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