首页 > 其他 > 详细

Codeforces Round #719 (Div. 3) C. Not Adjacent Matrix(构造)

时间:2021-05-07 00:45:56      阅读:22      评论:0      收藏:0      [点我收藏+]

We will consider the numbers ??a and ??b as adjacent if they differ by exactly one, that is, |?????|=1|a?b|=1.

We will consider cells of a square matrix ??×??n×n as adjacent if they have a common side, that is, for cell (??,??)(r,c) cells (??,???1)(r,c?1), (??,??+1)(r,c+1), (???1,??)(r?1,c) and (??+1,??)(r+1,c) are adjacent to it.

For a given number ??n, construct a square matrix ??×??n×n such that:

  • Each integer from 11 to ??2n2 occurs in this matrix exactly once;
  • If (??1,??1)(r1,c1) and (??2,??2)(r2,c2) are adjacent cells, then the numbers written in them must not be adjacent.

Input

The first line contains one integer ??t (1≤??≤1001≤t≤100). Then ??t test cases follow.

Each test case is characterized by one integer ??n (1≤??≤1001≤n≤100).

Output

For each test case, output:

  • -1, if the required matrix does not exist;
  • the required matrix, otherwise (any such matrix if many of them exist).

The matrix should be outputted as ??n lines, where each line contains ??n integers.

Example

input

Copy

3
1
2
3

output

Copy

1
-1
2 9 7
4 6 3
1 8 5

考虑进行如下构造:

for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= n; j++) {
				int now = i + (j - 1) * n;
				int nx = i, ny = (i + (j - 1));
				if(ny > n) ny = (ny % (n + 1) + 1);
				m[nx][ny] = now;
			}
		}

即:

1 5 9
 2 6 10
  3 7 11
   4 8 12...

越界的话模一下。这样能保证相差1的一定在斜对角线。注意构造完后遍历一遍判断是否有非法情况,有的话(其实只有n = 2是不可行的)则输出-1.

#include <bits/stdc++.h>
using namespace std;
int n;
int m[105][105];
int d[4][2] = {{0,1}, {0, -1}, {1, 0}, {1, 0}};
bool check(int x, int y) {
	for(int i = 0; i < 4; i++) {
		int nx = x + d[i][0], ny = y + d[i][1];
		if(m[nx][ny] == 0) continue;
		if(abs(m[x][y] - m[nx][ny]) == 1) return 0;
	}
	return 1;
}
int main() {
	int t;
	cin >> t;
	while(t--) {
		cin >> n;
		memset(m, 0, sizeof(m));
		bool flag = 1;
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= n; j++) {
				int now = i + (j - 1) * n;
				int nx = i, ny = (i + (j - 1));
				if(ny > n) ny = (ny % (n + 1) + 1);
				m[nx][ny] = now;
			}
		}
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= n; j++) {
				if(!check(i, j)) {
					flag = 0;
					break;
				}
			}
		}
		if(flag) {
			for(int i = 1; i <= n; i++) {
				for(int j = 1; j <= n; j++) {
					cout << m[i][j] << " ";
				}
				cout << endl;
			}
		} else cout << -1 << endl;
	}
	return 0;
}

Codeforces Round #719 (Div. 3) C. Not Adjacent Matrix(构造)

原文:https://www.cnblogs.com/lipoicyclic/p/14736492.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!