具体看代码以及分析;
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[40][40],f[40][40][40],t,x[40],old[40][40][40];//我把设的未知量看成是向量,每个未知量代表向量的一个方向
//old表示实际上这个格子在这个方向上按了多少下,f表示这个格子在某个方向的数值
int p[40][40],rev[4],all[40][40];//这些数组是用来算值的
//这题的关键就是先设第一排第一个格子按了x1,第二个格子按了x2。。。。然后现在每个格子都有一个具体数值,我们按下一排就是为了让每个方向都为0,就好了。具体见代码
int n, m;
int getans(int i, int j, int k)
{
int sum = (f[i][j - 1][k] + 2 * f[i][j][k] + f[i][j + 1][k])%3;
sum = ((3 - sum) + 3) % 3;
return sum;
}
void guss()
{
int kk = 1;
int biaoji[40];//标记
for (int i = 1; i <= m+1; i++)
biaoji[i] = 0,x[i]=0;
for (int i = 1; i <= m; i++)
{
for (int j = kk + 1; j <= m; j++)
{
if ((p[j][i] < p[kk][i] && p[j][i] != 0) || (p[j][i] != 0 && p[kk][i] == 0))
{
swap(p[j], p[i]);
}
}
if (p[kk][i] == 0)
continue;
biaoji[kk] = i;
for (int j = kk + 1; j <= m; j++)
{
int qq = p[j][i] / p[kk][i];
p[j][i] = 0;
for (int k = i + 1; k <= m + 1; k++)
{
p[j][k] = p[j][k] - qq*p[kk][k];
p[j][k] = ((p[j][k] % 3) + 3) % 3;
}
}
kk++;
}
if (biaoji[kk] == 0)
kk--;
for (int i = kk; i >= 1; i--)
{
int sum = p[i][m + 1];
for (int j = m; j > biaoji[i] ; j--)
sum += p[i][j] * x[j];
sum = sum*(-1);
sum = ((sum % 3)+3)%3;
x[biaoji[i]] = rev[p[i][biaoji[i]]] * sum;
x[biaoji[i]] = (x[biaoji[i]] % 3+3)%3;
}
int ans = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
int all1 = old[i][j][m + 1];
for (int k = 1; k <= m; k++)
{
all1 += old[i][j][k] * x[k];
}
all[i][j] = (all1%3+3)%3;
ans += all[i][j];
}
}
printf("%d\n", ans);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
for (int k = 0; k < all[i][j]; k++)
printf("%d %d\n", i, j);
}
}
int main()
{
scanf("%d", &t);
rev[0] = 0; rev[1] = 1; rev[2] = 2;
while (t--)
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
scanf("%d", &a[i][j]);
}
for (int i = 0; i <= n+1; i++)//一定要从0开始不然会错,但不知为什么有待思考
{
for (int j = 0; j <= m+1; j++)
{
all[i][j] = 0;
for (int k = 0; k <= m+1; k++)
{
f[i][j][k] = 0;
old[i][j][k] = 0;
}
}
}
for (int j = 1; j <= m; j++)
{
f[1][j][j] = 2; f[1][j][m + 1] = a[1][j]; old[1][j][j]=1;
if (j - 1 >= 1)
f[1][j][j - 1] = 1;
if (j + 1 <= m)
f[1][j][j + 1] = 1;
}
for (int i = 2; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
f[i][j][m + 1] = (old[i - 1][j][m + 1] + getans(i - 1, j, m+1)+a[i][j])%3;//old是上面一排按的对现在这排这个格子的影响,getans是为了让上一排各个方向为0,
//本排的左右以及自己按的对现在这个格子的
old[i][j][m + 1] = ((3 - f[i - 1][j][m + 1]) % 3 + 3) % 3;
for (int k = 1; k <= m; k++)
{
f[i][j][k] = (getans(i - 1, j, k)+old[i-1][j][k])%3;
old[i][j][k] = ((3 - f[i - 1][j][k]) % 3 + 3) % 3;
}
}
}
for (int j = 1; j <= m; j++)
{
for (int k = 1; k <= m + 1; k++)
{
p[j][k] = f[n][j][k];//列方程的依据就是各个方向都为0
}
}
guss();
}
}