C. No Prime Differences

C. No Prime Differences

You are given integers n and m. Fill an n by m grid with the integers 1 through nm, 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 t (1t1000) — the number of test cases. The description of the test cases follows.

The first and only line of each test case contains two integers n and m (4n,m1000) — the dimensions of the grid.

It is guaranteed that the sum of nm over all test cases does not exceed 106.

Output

For each test case, output n lines of m integers each, representing the final grid. Every number from 1 to nm 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.

Example

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
复制代码

Note

The first sample case corresponds to the picture above. The only absolute differences between adjacent elements in this grid are 1, 4, 6, 8, and 9, none of which are prime.

 

解题思路

  昨晚爆0了,思维构造题完全不会做,说不出的难受。

  我们从矩阵的左上角开始,从左往右,从上往下,依次填入1nm,例如下图:

  可以发现任意两个元素的差值不是1(同一行内相邻两元素)就是m(同一列内相邻两元素)。所以如果m不是质数那么已经构造完了。而如果m是质数(参考上图),那么就交换行的顺序,把原矩阵的前n2行放置到矩阵的偶数行(2,4,6,),把剩下的n2行放置到奇数行(1,3,5,),参考下图:

  这样做带来的效果是,同一列中任意两个相邻元素的差值为m的倍数,即不可能是质数。同时这种构造方式又保证了没有一行与其原始邻居相邻,这是因为n4,因此任意两行的差值至少为n2×m2m,而m的倍数很明显不是质数。

  AC代码如下,时间复杂度为O(nm)

复制代码
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int N = 1010;
 5 
 6 int ans[N][N];
 7 
 8 void solve() {
 9     int n, m;
10     scanf("%d %d", &n, &m);
11     for (int i = 1, k = 1; i <= n; i++) {
12         for (int j = 1; j <= m; j++) {
13             ans[i][j] = k++;
14         }
15     }
16     for (int i = 1; i <= n; i++) {
17         for (int j = 1; j <= m; j++) {
18             if (i & 1) printf("%d ", ans[n / 2 + (i + 1) / 2][j]);
19             else printf("%d ", ans[i >> 1][j]);
20         }
21         printf("\n");
22     }
23 }
24 
25 int main() {
26     int t;
27     scanf("%d", &t);
28     while (t--) {
29         solve();
30     }
31     
32     return 0;
33 }
复制代码

 

参考资料

  Codeforces Round #877 (Div. 2) Editorial:https://codeforces.com/blog/entry/116995

posted @   onlyblues  阅读(166)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
历史上的今天:
2022-06-05 无线网络
Web Analytics
点击右上角即可分享
微信分享提示