KSzsh

导航

Matrix of Differences(构造)

题目链接

题目描述:

For a square matrix of integers of size \(n×n\), let's define its beauty as follows: for each pair of side-adjacent elements \(x\) and \(y\), write out the number \(|x−y|\), and then find the number of different numbers among them.

For example, for the matrix \( \left( \begin{matrix} 1 & 4 \\ 3 & 2 \end{matrix} \right) \) the numbers we consider are \(|1−3|=2\), \(|1−4|=3\), \(|3−2|=1\) and \(|4−2|=2\); there are \(3\) different numbers among them \((2, 3 and 1)\), which means that its beauty is equal to \(3\).

You are given an integer \(n\). You have to find a matrix of size \(n×n\), where each integer from \(1\) to \(n^2\) occurs exactly once, such that its beauty is the maximum possible among all such matrices.

输入描述:

The first line contains a single integer \(t (1≤t≤49)\) – the number of test cases.

The first (and only) line of each test case contains a single integer \(n (2≤n≤50)\).

输出描述:

For each test case, print \(n\) rows of \(n\) integers — a matrix of integers of size \(n×n\), where each number from \(1\) to \(n^2\) occurs exactly once, such that its beauty is the maximum possible among all such matrices. If there are multiple answers, print any of them.

样例:

input:

2
2
3

output:

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

AC代码:

#include <bits/stdc++.h>

using namespace std;

int n;

void solve()
{
	cin >> n;

	// 相当与一个n * n的二维数组,可以用a[][]来表示,但n不宜太大
	vector<vector<int>> a(n, vector<int> (n));

	int l = 1, r = n * n, t = 0;

	// 蛇形排列
	// 第一行从左到右,第二行从右到左,第三行从左到右...依此类推
	for(int i = 0; i < n; i ++)
	{
		for(int j = 0; j < n; j ++)
		{
			if(t)
			{
				a[i][j] = l ++;
			}
			else
			{
				a[i][j] = r --;
			}

			t ^= 1;
		}

		if(i & 1)
		{
			reverse(a[i].begin(), a[i].end());
		}
	}

	for(int i = 0; i < n; i ++)
	{
		for(int j = 0; j < n; j ++)
		{
			// 相当于一个字符串a = " \n";
			// 输出a[0] 或者 a[1];
			cout << a[i][j] << " \n"[j == n - 1];
		}
	}
}

int main()
{
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);

	int T;
	cin >> T;

	while(T --)
		solve();

	return 0;
}

posted on 2023-01-10 09:58  KSzh  阅读(45)  评论(0编辑  收藏  举报