高斯消元模版题,但怎样建立方程组不容易想,请参考http://blog.csdn.net/shiren_Bod/article/details/5766907
#include <iostream>
using namespace std;
#define hmax 30
#define lmax 30
int map[hmax][lmax+1];
int ans[lmax];
inline int gcd(int a,int b)
{
if(b==0) return a;
else return gcd(b,a%b);
}
inline int lcm(int a,int b)
{
return a*b/gcd(a,b);
}
void gauss()
{
int hs,ls,curhs,max,lc,tch,th,temp;
for(ls=0,hs=0;ls<lmax&&hs<hmax;++ls,++hs)
{
max=hs;
for(curhs=hs+1;curhs<hmax;++curhs)
{
if(abs(map[curhs][ls])>abs(map[hs][ls])) max=curhs;
}
if(max!=hs)
{
for(int j=0;j<lmax+1;++j) swap(map[hs][j],map[max][j]);
}
if(map[hs][ls]==0) {hs--;continue;}
for(curhs=hs+1; curhs<hmax; ++curhs)
{
if(map[curhs][ls]!=0)
{
lc=lcm(abs(map[curhs][ls]),abs(map[hs][ls]));
tch=lc/abs(map[curhs][ls]);
th=lc/abs(map[hs][ls]);
if(map[curhs][ls]*map[hs][ls]<0) th=-th;
for(int j=ls;j<lmax+1;++j)
{
map[curhs][j]=(map[curhs][j]*tch-map[hs][j]*th+10000)%2;
}
}
}
}
for(int i=hmax-1;i>=0;--i)
{
temp=map[i][lmax];
for(int j=i+1;j<hmax;++j)
{
if(map[i][j]!=0) temp-=map[i][j]*ans[j];
}
if(map[i][i]) ans[i]=temp/map[i][i];
else ans[i]=0;
ans[i]=(ans[i]+10000)%2;
}
}
int main()
{
int i,j,k,kn,km,kx,ky,t;
scanf("%d",&t);
for(k=1; k<=t; k++)
{
memset(map, 0, sizeof(map));
for(i=0; i<30; i++)
{
scanf("%d", &map[i][30]);
ans[i] = 0;
}
for(i=0; i<30; i++)
{
kn = i / 6;
km = i % 6;
for(j=0; j<30; j++)
{
kx = j / 6;
ky = j % 6;
if(abs(kx - kn) + abs(ky - km) <= 1)
map[i][j] = 1;
else
map[i][j] = 0;
}
}
gauss();
printf("PUZZLE #%d\n",k);
for(i=0; i<30; i++)
{
printf("%d", ans[i]);
if((i+1) % 6 == 0)
printf("\n");
else
printf(" ");
}
}
//system("pause");
return 0;
}