题意:给n*n的网格图的边染k种颜色,每种色染的边数相同,构造不存在同色环及整行整列不同色的方案。
题解:思维
n=1,k=1,2 * (n + 1) * n % k != 0 这三种情况肯定是不行的。
接下来考虑两种情况。
①n % k != 0
这个直接一行一行颜色从1到k顺着涂就行了,再接到列上。
②n % k = 0
如果按照上述方法涂,会出现同色环,我们这样涂:
假如n=3,k=3,对于行来说
1 2 3
2 3 1
3 1 2
即每次开头涂的颜色往后挪一位。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
int t, n, k;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &k);
if (n == 1 || k == 1 || (2 * (n + 1) * n) % k != 0) puts("-1");
else {
if (n % k != 0) {
int x = 1;
for (int i = 1; i <= n + 1; i++) {
for (int j = 1; j <= n; j++) {
printf("%d ", (x - 1) % k + 1);
++x;
}
puts("");
}
for (int i = 1; i <= n + 1; i++) {
for (int j = 1; j <= n; j++) {
printf("%d ", (x - 1) % k + 1);
++x;
}
puts("");
}
}
else {
int x = 1;
for (int i = 1; i <= n + 1; i++) {
x = (i - 1) % k + 1;
for (int j = 1; j <= n; j++) {
printf("%d ", (x - 1) % k + 1);
++x;
}
puts("");
}
for (int i = 1; i <= n + 1; i++) {
x = (i - 1) % k + 1;
for (int j = 1; j <= n; j++) {
printf("%d ", (x - 1) % k + 1);
++x;
}
puts("");
}
}
}
}
return 0;
}