题目链接:https://codeforces.com/contest/1783/problem/B
题干:
For a square matrix of integers of size n×nn×n, let's define its beauty as follows: for each pair of side-adjacent elements xx and yy, write out the number |x−y||x−y|, and then find the number of different numbers among them.
For example, for the matrix (1432)(1342) the numbers we consider are |1−3|=2|1−3|=2, |1−4|=3|1−4|=3, |3−2|=1|3−2|=1 and |4−2|=2|4−2|=2; there are 33 different numbers among them (22, 33 and 11), which means that its beauty is equal to 33.
You are given an integer nn. You have to find a matrix of size n×nn×n, where each integer from 11 to n2n2 occurs exactly once, such that its beauty is the maximum possible among all such matrices.
Input
The first line contains a single integer tt (1≤t≤491≤t≤49) – the number of test cases.
The first (and only) line of each test case contains a single integer nn (2≤n≤502≤n≤50).
Output
For each test case, print nn rows of nn integers — a matrix of integers of size n×nn×n, where each number from 11 to n2n2 occurs exactly once, such that its beauty is the maximum possible among all such matrices. If there are multiple answers, print any of them.
要求:
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
思路:
让尽量相差大的数相临,从而得到尽量大的差,才能保证找到最多的数字。一开始考虑一排从前填一排从后填,相临着填,发现无法完成最优,考虑斜着填。如图所示:
考虑用bfs,对行列相加为奇数则从后往前,对偶数则从前天,用队列不断写入,再传入该点的右边和下边的坐标,注意判断边界和打标记,防止重复执行。
代码:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
int t,n;
int l,r;
int dx[2]={0,1};
int dy[2]={1,0};
int book[55][55]={0};
int vis[55][55]={0};
void bfs(){
int sx=1,sy=1;
book[sx][sy]=1;
vis[sx][sx]=1;
queue<pair<int,int> > q;
q.push({sx,sy});
while(!q.empty()){
int nx=q.front().first;
int ny=q.front().second;
q.pop();
if((nx+ny)%2==0){
book[nx][ny]=l;
l++;
}
else{
book[nx][ny]=r;
r--;
}
for(int i=0;i<2;i++){
int tx=nx+dx[i];
int ty=ny+dy[i];
if(tx<=n&&ty<=n&&vis[tx][ty]==0){
q.push({tx,ty});
vis[tx][ty]=1;
}
}
}
}
int main()
{
cin>>t;
while(t--){
cin>>n;
memset(book,0,sizeof(book));
memset(vis,0,sizeof(vis));
int count=0;
l=1;
r=n*n;
bfs();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<book[i][j]<<" ";
}
cout<<endl;
}
}
return 0;
}
ps:最优解可能不止一种哦。