C. No Prime Differences

发布时间 2023-06-05 15:26:15作者: onlyblues

C. No Prime Differences

You are given integers $n$ and $m$. Fill an $n$ by $m$ grid with the integers $1$ through $n\cdot 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 $t$ ($1 \le t \le 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 $n$ and $m$ ($4 \le n, m \le 1000$) — the dimensions of the grid.

It is guaranteed that the sum of $n\cdot m$ over all test cases does not exceed $10^6$.

Output

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

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$了,思维构造题完全不会做,说不出的难受。

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

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

  这样做带来的效果是,同一列中任意两个相邻元素的差值为$m$的倍数,即不可能是质数。同时这种构造方式又保证了没有一行与其原始邻居相邻,这是因为$n \geq 4$,因此任意两行的差值至少为$\left\lceil \frac{n}{2} \right\rceil \times m \geq 2m$,而$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