KSzsh

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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 |xy|, and then find the number of different numbers among them.

For example, for the matrix (1432) the numbers we consider are |13|=2, |14|=3, |32|=1 and |42|=2; there are 3 different numbers among them (2,3and1), 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 n2 occurs exactly once, such that its beauty is the maximum possible among all such matrices.

输入描述:

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

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

输出描述:

For each test case, print n rows of n integers — a matrix of integers of size n×n, where each number from 1 to n2 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   KSzh  阅读(48)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示