POJ 1681---Painter's Problem(高斯消元)
Description
There is a square wall which is made of n*n small square bricks. Some bricks are white while some bricks are yellow. Bob is a painter and he wants to paint all the bricks yellow. But there is something wrong with Bob's brush. Once he uses this brush to paint brick (i, j), the bricks at (i, j), (i-1, j), (i+1, j), (i, j-1) and (i, j+1) all change their color. Your task is to find the minimum number of bricks Bob should paint in order to make all the bricks yellow.
Input
The first line contains a single integer t (1 <= t <= 20) that indicates the number of test cases. Then follow the t cases. Each test case begins with a line contains an integer n (1 <= n <= 15), representing the size of wall. The next n lines represent the original wall. Each line contains n characters. The j-th character of the i-th line figures out the color of brick at position (i, j). We use a 'w' to express a white brick while a 'y' to express a yellow brick.
Output
For each case, output a line contains the minimum number of bricks Bob should paint. If Bob can't paint all the bricks yellow, print 'inf'.
Sample Input
2
3
yyy
yyy
yyy
5
wwwww
wwwww
wwwww
wwwww
wwwww
Sample Output
0
15
Source
代码如下:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn = ; int equ,var;
int a[maxn][maxn];
int x[maxn]; // 解集.
int pos[maxn];
///int free_num; void init_a()///对称阵;
{
memset(a,,sizeof(a));
for(int i=;i<var*var;i++)
{
a[i][i]=;
int t=i%var;
if(t>) a[i][i-]=;
if(t<var-) a[i][i+]=;
t=i/var;
if(t>=) a[i][i-var]=;
if(t<var-) a[i][i+var]=;
}
} int Gauss()
{
int i, j, k;
int max_r; // 当前这列绝对值最大的行.
int t=;///记录*元的个数;
int col = ; /// 当前处理的列. for (k = ; k < equ*equ && col < var*var; k++, col++)
{
max_r = k;
for (i = k + ; i < equ*equ; i++)
{
if (a[i][col] > a[max_r][col])
{
max_r=i;
break;
}
}
if (max_r != k)
{
for (j = k; j < var*var + ; j++) swap(a[k][j], a[max_r][j]);
}
if (a[k][col] == )
{
/// 说明该col列第k行以下全是0了,则处理当前行的下一列.
///并且应当记录这个*元;
k--;
pos[t++]=col;
continue;
}
for (i = k + ; i < equ*equ; i++)
{
if (a[i][col] != )
{
for (j = col; j < var*var + ; j++)
{
a[i][j]^=a[k][j];
}
}
}
}
for (i = k; i < equ*equ; i++)
{
// 对于无穷解来说,如果要判断哪些是*变元,那么初等行变换中的交换就会影响,则要记录交换.
if (a[i][col] != ) return -;
}
return var*var - k;
} int solve(int s)
{
int ans=;
int state=(<<s);
for(int i=;i<state;i++)
{
int cnt=;
memset(x,,sizeof(x));
for(int j=;j<s;j++)
{
if(i&(<<j)) x[pos[j]]=,cnt++;
}
for(int j=var*var-s-;j>=;j--)
{
int f=;
int ss;
int tmp=a[j][var*var];
for(int k=j;k<equ*equ;k++)
{
if(a[j][k]&&f)
{
ss=k;
f=;
}
if(a[j][k]) tmp^=x[k];
}
x[ss]=tmp;
cnt+=x[ss];
}
ans=min(ans,cnt);
}
return ans;
} int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&equ);
var=equ;
init_a();
for(int i=;i<var*var;i++)
{
char x;
cin>>x;
if(x=='y')
a[i][var*var]=;
else a[i][var*var]=;
}
int v=Gauss();
if(v==-) printf("inf\n");
else cout<<solve(v)<<endl;
}
return ;
}