HDU 5755 Gambler Bo
可以设n*m个未知量,建立n*m个方程。位置i,j可以建立方程 (2*x[i*m+j]+x[(i-1)*m+j]+x[(i+1)*m+j]+x[i*m+j-1]+x[i*m+j+1])%3=3-b[i][j]; 套了个高斯消元的板子过了。
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<map> #include<set> #include<queue> #include<stack> #include<iostream> using namespace std; typedef long long LL; const double pi=acos(-1.0),eps=1e-8; void File() { freopen("D:\\in.txt","r",stdin); freopen("D:\\out.txt","w",stdout); } inline int read() { char c = getchar(); while(!isdigit(c)) c = getchar(); int x = 0; while(isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); } return x; } const int mod = 3; int exgcd(int a,int b,int &x,int &y){ if(!b){x = 1; y = 0; return a;} else{ int r = exgcd(b,a%b,y,x); y -= x * (a/b); return r; } } int lcm(int a,int b){ int x = 0, y =0; return a / exgcd(a,b,x,y) * b; } const int MAXN=1000; int A[MAXN][MAXN],free_x[MAXN],x[MAXN]; void Gauss(int n,int m){ int r,c; for(r=0,c=0;r<n && c<m;c++){ int maxr = r; for(int i=r+1;i<n;i++) if(abs(A[i][c]) > abs(A[maxr][c])) maxr = i; if(maxr != r) for(int i=c;i<=m;i++) swap(A[r][i],A[maxr][i]); if(!A[r][c]) continue; for(int i=r+1;i<n;i++) if(A[i][c]){ int d = lcm(A[i][c],A[r][c]); int t1 = d / A[i][c], t2 = d / A[r][c]; for(int j=c;j<=m;j++) A[i][j] = ((A[i][j] * t1 - A[r][j] * t2) % mod + mod) % mod; } r++; } for(int i=r;i<n;i++) if(A[i][m]) return ; for(int i=r-1;i>=0;i--){ x[i] = A[i][m]; for(int j=i+1;j<m;j++){ x[i] = ((x[i] - A[i][j] * x[j]) % mod + mod) % mod; } int x1 = 0,y1 = 0; int d = exgcd(A[i][i],mod,x1,y1); x1 = ((x1 % mod) + mod) % mod; x[i] = x[i] * x1 % mod; } } void Gauss_init(){ memset(A,0,sizeof A); memset(free_x,0,sizeof free_x); memset(x,0,sizeof x); } int T,n,m; int b[MAXN][MAXN]; bool check(int a,int b) { if(a>=0&&a<n&&b>=0&&b<m) return 1; return 0; } int main() { scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); for(int i=0;i<n;i++) for(int j=0;j<m;j++) scanf("%d",&b[i][j]); Gauss_init(); for(int i=0;i<n;i++) for(int j=0;j<m;j++) { A[i*m+j][i*m+j]=2; if(check(i-1,j)) A[i*m+j][(i-1)*m+j]=1; if(check(i+1,j)) A[i*m+j][(i+1)*m+j]=1; if(check(i,j-1)) A[i*m+j][i*m+j-1]=1; if(check(i,j+1)) A[i*m+j][i*m+j+1]=1; A[i*m+j][n*m]=(3-b[i][j])%3; } Gauss(n*m,n*m); int ans=0; for(int i=0;i<n*m;i++) ans=ans+x[i]; printf("%d\n",ans); for(int i=0;i<n*m;i++) while(x[i]) { printf("%d %d\n",i/m+1,i%m+1); x[i]--; } } return 0; }