1. 程式人生 > 實用技巧 >I - 開關問題

I - 開關問題

POJ - 1830

高斯消元求異或方程組。

每個燈連續操作兩次等於沒有操作,所以每盞燈只有0/1的操作狀態,記為\(x_i\)

\(i\)盞燈對第\(j\)盞燈有影響,則\(a_{j,i} = 1\),反之\(a_{j,i} = 0\)

\(i\)盞燈初末狀態不一樣,\(a_{i,n+1} = 1\)反之為\(0\)

然後我們得到矩陣

\[\left[ \begin{array}{ccc} a_{1,1} & a_{1,2} & \ldots & a_{1,n} & | & a_{1,n + 1} \\\\ a_{2,1} & a_{2,2} & \ldots & a_{2,n} & | & a_{2,n + 1} \\\\ \vdots & \vdots & \vdots & \vdots & | & \vdots \\\\ a_{n,1} & a_{n,2} & \ldots & a_{n,n} & | & a_{1,n + 1} \\\\ \end{array} \right] \]

直接高斯消元,用異或消去其他位上的\(1\)

如果出現第\(j\)列上所有的\(1\)都消去了,那麼第\(j\)盞燈操不操作都可以,我們稱為一個自由元。

統計自由元的個數\(k\)\(Ans = 2^k\)

如果第\(i\)\(a_{i,1} ~ a_{i,n}\)均為\(0\),但是\(a_{i,n+1} = 1\)則無解。

以上


#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

int n;

int a[35],b[35];
int g[35][35];

long long ksm(long long x,int y){
    long long z = 1;
    while(y){
        if(y & 1) z = z * x;
        y >>= 1;
        x = x * x;
    }
    return z;
}

int main(){
    int T; scanf("%d",&T);
    while(T --){
        memset(g,0,sizeof(g));
        
        scanf("%d",&n);
        for(int i = 1; i <= n; ++ i) scanf("%d",&a[i]);
        for(int i = 1; i <= n; ++ i) scanf("%d",&b[i]);
        
        for(int i = 1; i <= n; ++ i) if(a[i] == b[i]) g[i][n + 1] = 0; else g[i][n + 1] = 1;
        
        int x,y;
        while(1){
            scanf("%d%d",&x,&y);
            if(x == 0 && y == 0) break;
            g[y][x] = 1;
        }
        
        for(int i = 1; i <= n; ++ i) g[i][i] = 1;
        
        int now = 1;
        for(int i = 1; i <= n; ++ i){
            bool flag = 0; int pos = -1;
            for(int j = now; j <= n; ++ j){
                if(g[j][i] == 1) { flag = 1; pos = j; break; }
            }
            if(!flag) continue;
            for(int j = 1; j <= n + 1; ++ j) swap(g[now][j],g[pos][j]);
            
            for(int j = now + 1; j <= n; ++ j){
                if(g[j][i] == 0) continue;
                for(int k = 1; k <= n + 1; ++ k) 
                g[j][k] ^= g[now][k];
            }
            
            ++ now;
        }
        bool flag = 1;
        for(int i = now; i <= n; ++ i){
            if(g[i][n + 1] != 0) { flag = 0; break; }
        }
        if(!flag) puts("Oh,it's impossible~!!");
        else{
            printf("%lld\n",ksm(2, n - now + 1));
        }
    }
    return 0;
}