Codeforces 1838C No Prime Differences

题目描述:

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

You are given integers nn and mm. Fill an nn by mm grid with the integers 11 through n⋅mn⋅m, in such a way that for any two adjacent cells in the grid, the absolute difference of the values in those cells is not a prime number. Two cells in the grid are considered adjacent if they share a side.

It can be shown that under the given constraints, there is always a solution.

Input

The first line of the input contains a single integer tt (1≤t≤10001≤t≤1000) — the number of test cases. The description of the test cases follows.

The first and only line of each test case contains two integers nn and mm (4≤n,m≤10004≤n,m≤1000) — the dimensions of the grid.

It is guaranteed that the sum of n⋅mn⋅m over all test cases does not exceed 106106.

Output

For each test case, output nn lines of mm integers each, representing the final grid. Every number from 11 to n⋅mn⋅m should appear exactly once in the grid.

The extra spaces and blank lines in the sample output below are only present to make the output easier to read, and are not required.

If there are multiple solutions, print any of them.

input

3
4 4
5 7
6 4

output

16  7  1  9
12  8  2  3
13  4 10 11
14  5  6 15

29 23 17  9  5  6  2
33 27 21 15 11  7  1
32 31 25 19 20 16 10
26 30 24 18 14  8  4
35 34 28 22 13 12  3

 2  3  7 11
 8  9  1 10
17 13  5  4
18 14  6 12
19 23 15 21
20 24 16 22

题目大意:将1-m*n填充在n*m个格子当中,要求相邻格子之间差的绝对值不能为素数。

思路分析:素数的倍数肯定不为素数,非素数的倍数也不为素数。所以,如果n不是素数,我们可以让每行之间相差1,每列之间相差n;如果m不是素数,我们可以让每列之间相差1,每行之间相差m;若n和m都为素数,那么可以让每列之间相差1,每行之间相差m的倍数。

代码:

#include<iostream>
using namespace std;
bool s[1005];
void init(){
	s[0]=1;
	s[1]=1;
	for(int i=2;i<=1000;i++){
		if(s[i]==0){
			for(int j=2*i;j<=1000;j+=i)
			s[j]=1;
		}
	}
}
int main(){
	int t;
	cin>>t;
	init();
	while(t--){
		int n,m;
		cin>>n>>m;
		if(s[m]){
			for(int i=1;i<=n*m;i++){
				cout<<i<<" ";
				if(i%m==0)
				cout<<endl;
			}
		}
		else
		if(s[n]){
			for(int i=1;i<=n;i++){
				int k=i;
				for(int j=1;j<=m;j++){
					cout<<k<<" ";
					k+=n;
				}
				cout<<endl;
			}
		}
		else{
			int be=1;
			for(int i=1;i<=n;i+=2){
				for(int j=1;j<=m;j++){
					cout<<be+j-1<<" ";
				}
				cout<<endl;
				be+=2*m;
			}
			be=1+m;
			for(int i=2;i<=n;i+=2){
				for(int j=1;j<=m;j++){
					cout<<be+j-1<<" ";	
				}
				cout<<endl;
				be+=m*2;
			}
		}
		cout<<endl;
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值