POJ 1681 Painter's Problem 高斯消元 枚举自由变量

题目链接:http://poj.org/problem?id=1681

和POJ 1753 一样

代码:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#define sf scanf
#define pf printf
using namespace std;
const int maxn = 400,INF = 0x3f3f3f3f;
typedef int Matrix[maxn][maxn];
const int step[][2] = { {0,0} , {-1,0} , {1,0} , {0,1} , {0,-1} };
Matrix A;
int ANS[maxn],n;
void init(){
    memset(A,0,sizeof A);
    int i,j,k,c_pos,n_pos,cx,cy,nx,ny;
    for(i = 0;i < n;++i){
        for(j = 0;j < n;++j){
            c_pos = i * n + j;
            for(k = 0;k < 5;++k){
                nx = i + step[k][0],ny = j + step[k][1];
                if(nx >= 0 && nx < n && ny >= 0 && ny < n){
                    A[nx * n + ny][c_pos] = 1;
                }
            }
        }
    }
}

int Gauss(Matrix A,int n){
    int i,j,k,p;
    for(i = j = 0;j < n && i < n;++j){
        k = i;
        for(p = i + 1;p < n;++p) if(A[p][j] > A[k][j]) k = p;
        if(A[k][j]){
            for(p = 0;p <= n;++p) swap(A[i][p],A[k][p]);
            for(k = i + 1;k < n;++k){
                if(A[k][j]){
                    for(p = j;p <= n;++p) A[k][p] = (A[k][p] - A[i][p] + 2) % 2;
                }
            }
            i++;
        }
    }
    for(k = i;k < n;++k) if(A[k][n]) return INF;
    int cnt = n - i,minAns = INF,tmpAns;
    for(int st = 0;st < (1 << cnt);++st){
        tmpAns = 0;
        for(j = i;j < n;++j) tmpAns += (ANS[j] = ((st >> (n - j - 1)) & 1));
        for(j = i - 1;j >= 0;--j){
            int tmp = 0;
            for(p = j + 1;p < n;++p) tmp = (tmp + A[j][p] * ANS[p]) % 2;
            ANS[j] = ( (A[j][n] - tmp) % 2 + 2 ) % 2;
            tmpAns += ANS[j];
        }
        minAns = min(tmpAns,minAns);
    }
    return minAns;
}
char tmpc;
int main(){
    int T;sf("%d",&T);
    while(T--){
        sf("%d",&n);
        init();getchar();
        for(int i = 0;i < n * n;++i){
            while((tmpc = getchar()) == '\n');
            if(tmpc == 'y') A[i][n * n] = 0;
            else A[i][n * n] = 1;
        }
        int ans = Gauss(A,n * n);
        if(ans == INF) pf("inf\n");
        else pf("%d\n",ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值