P3164 [CQOI2014] 和谐矩阵

题意

给出 \(n,m\),要求构造一个 \(n\times m\)\(01\) 矩阵,使得每个点本身以及上下左右的点中 \(1\) 的数量是偶数。
\(n,m\le40\)

思路

设矩阵第 \(i\) 行第 \(j\) 列的元素是 \(a_{i,j}\),如果令矩阵外的元素全部是 \(0\),那么有 \(a_{i-1,j}\oplus a_{i,j-1}\oplus a_{i+1,j}\oplus a_{i,j+1}=0\),用高斯消元解方程组,找到一组不是全零的解并输出。

代码

// Problem: P3164 [CQOI2014] 和谐矩阵
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P3164
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
namespace IO{
    template<typename T>
    inline void read(T&x){
        x=0;char c=getchar();bool f=0;
        while(!isdigit(c)) c=='-'?f=1:0,c=getchar();
        while(isdigit(c)) x=x*10+c-'0',c=getchar();
        f?x=-x:0;
    }
    template<typename T>
    inline void write(T x){
        if(x==0){putchar('0');return ;}
        x<0?x=-x,putchar('-'):0;short st[50],top=0;
        while(x) st[++top]=x%10,x/=10;
        while(top) putchar(st[top--]+'0');
    }
    inline void read(char&c){c=getchar();while(isspace(c)) c=getchar();}
    inline void write(char c){putchar(c);}
    inline void read(string&s){s.clear();char c;read(c);while(!isspace(c)&&~c) s+=c,c=getchar();}
    inline void write(string s){for(int i=0,len=s.size();i<len;i++) putchar(s[i]);}
    template<typename T>inline void write(T*x){while(*x) putchar(*(x++));}
    template<typename T,typename...T2> inline void read(T&x,T2&...y){read(x),read(y...);}
    template<typename T,typename...T2> inline void write(const T x,const T2...y){write(x),putchar(' '),write(y...),sizeof...(y)==1?putchar('\n'):0;}
}using namespace IO;
const int maxn=50;
bitset<40*40+10>a[maxn*maxn];
int bh[maxn][maxn],cnt_bh,fx[10]={0,0,0,1,-1},fy[10]={0,1,-1},ans[maxn*maxn];
void work(int n){
    for(int i=1;i<=n;i++){
        for(int j=i;j<=n;j++) if(a[j].test(i)){swap(a[j],a[i]);break;}
        if(!a[i].test(i)) continue;
        for(int j=i+1;j<=n;j++){
            if(!a[j].test(i)) continue;
            a[j]^=a[i];
        }
    }
    for(int i=n;i>=1;i--){
        int bs=0;
        if(!a[i].test(i)){ans[i]=1;continue;}
        for(int j=1;j<=n;j++) if(a[i].test(j)) bs^=ans[j];
        ans[i]=bs^a[i].test(n+1);
    }
}
signed main(){
    int n,m;read(n,m);
    for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) bh[i][j]=++cnt_bh;
    for(int i=1;i<=n;i++) for(int j=1;j<=m;j++){
        for(int f=1;f<=4;f++){
            int x=i+fx[f],y=j+fy[f];
            if(x<1||y<1||x>n||y>m) continue;
            a[bh[i][j]].set(bh[x][y]);
        }
        a[bh[i][j]].set(bh[i][j]);
    }
    work(cnt_bh);
    for(int i=1;i<=n;i++,write("\n")) for(int j=1;j<=m;j++) write(ans[bh[i][j]]),write(" ");
    return 0;
}
posted @ 2026-05-21 19:18  Link-Cut_Trees  阅读(12)  评论(0)    收藏  举报