P3631 [APIO2011] 方格染色 题解

· · 题解

将红色看作 1,蓝色看作 0,那么题目要求即为,对于所有的 x,y,满足:

a_{x,y}\oplus a_{x-1,y}\oplus a_{x,y-1} \oplus a_{x-1,y-1}=1

显然也应该满足:

a_{x-1,y}\oplus a_{x-2,y}\oplus a_{x-1,y-1} \oplus a_{x-2,y-1}=1

两式子合并,得:

a_{x,y}\oplus a_{x,y-1}\oplus a_{x-2,y}\oplus a_{x-2,y-1}=0

这个式子继续推广,最后可以得到结论:

a_{x,y}\oplus a_{x,y-1}\oplus a_{x-2t,y}\oplus a_{x-2t,y-1}=0

同理我们有:

a_{x,y-1}\oplus a_{x,y-2}\oplus a_{x-2t,y-1}\oplus a_{x-2t,y-2}=0

两式子合并,得:

a_{x,y}\oplus a_{x,y-2}\oplus a_{x-2t,y}\oplus a_{x-2t,y-2}=0

这个式子与上面的那个结论比较,可以得到结论:

a_{x,y}\oplus a_{x,y-k}\oplus a_{x-2t,y}\oplus a_{x-2t,y-k}=0

同理:

a_{x,y}\oplus a_{x,y-2*k}\oplus a_{x-t,y}\oplus a_{x-t,y-2*k}=0

因此,不难发现:

当 x 和 y 中有任意一个数字为奇数,则:

a_{x,y}\oplus a_{x,1}\oplus a_{1,y}\oplus a_{1,1}=0

否则,我们有:

a_{x,y}\oplus a_{x,1}\oplus a_{1,y}\oplus a_{1,1}=1

这个怎么证明呢?同机房大佬证出来了,我贴一个 剪贴板。

好了,准备工作完成了。

我们接下来发现确定了第一行和第一列之后就可以确定整个方案,原因很简单。

所以一开始空的方案数为 2^{n+m-1}。

再看看上面的式子,我们发现当 a_{1,1} 和 a_{x,y} 已知时可以推出 a_{x,1} 和 a_{1,y} 的关系就不难想到每个点对答案的贡献了。

因为一开始点与点之间的决策是独立的,而每个点相当于确定了他们之间的一些关系,所以用一个带权并查集维护即可。

设有 k 个连通块,则答案为 2^{k-1}。

#include<bits/stdc++.h>
#define LL long long
using namespace std;
const LL N=1e6;
const LL mod=1e9;
LL ksm(LL x,LL y)
{
    if(y<0)return 0;
    LL ans=1;
    while(y)
    {
        if(y&1)ans=ans*x%mod;
        x=x*x%mod,y>>=1; 
    }
    return ans;
}
LL n,m,k,fa[N],g[N],x[N],y[N],z[N],flg[2],ans;
LL find(LL x)
{
    if(fa[x]==x)return x;
    LL t=find(fa[x]);
    g[x]^=g[fa[x]];
    return fa[x]=t;
}
LL solve(LL a)
{
    for(int i=1;i<=n+m;i++)fa[i]=i,g[i]=0;
    fa[1]=1+n;
    for(int i=1;i<=k;i++)
    {
        LL fx=find(x[i]),fy=find(n+y[i]);
        LL t=z[i]^a;
        if(x[i]%2==0&&y[i]%2==0)t^=1;
        if(fx!=fy)fa[fx]=fy,g[fx]^=t^g[x[i]]^g[y[i]+n];
        else if(t!=g[x[i]]^g[y[i]+n])return 0;
    }
    LL cnt=0;
    for(int i=1;i<=n+m;i++)
    {
        if(find(i)==i)cnt++;
    }
    return ksm(2,cnt-1);
}
int main() 
{
    cin>>n>>m>>k;
    for(int i=1;i<=k;i++)
    {
        cin>>x[i]>>y[i]>>z[i];
        if(x[i]==1&&y[i]==1)flg[z[i]]=1,i--,k--;
    }
    if(!flg[1])ans=(ans+solve(0))%mod;
    if(!flg[0])ans=(ans+solve(1))%mod;
    cout<<ans<<endl;
}