C. No Prime Differences
C. No Prime Differences
You are given integers and . Fill an by grid with the integers through , 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 () — the number of test cases. The description of the test cases follows.
The first and only line of each test case contains two integers and () — the dimensions of the grid.
It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, output lines of integers each, representing the final grid. Every number from to 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 , , , , and , none of which are prime.
解题思路
昨晚爆了,思维构造题完全不会做,说不出的难受。
我们从矩阵的左上角开始,从左往右,从上往下,依次填入,例如下图:
可以发现任意两个元素的差值不是(同一行内相邻两元素)就是(同一列内相邻两元素)。所以如果不是质数那么已经构造完了。而如果是质数(参考上图),那么就交换行的顺序,把原矩阵的前行放置到矩阵的偶数行,把剩下的行放置到奇数行,参考下图:
这样做带来的效果是,同一列中任意两个相邻元素的差值为的倍数,即不可能是质数。同时这种构造方式又保证了没有一行与其原始邻居相邻,这是因为,因此任意两行的差值至少为,而的倍数很明显不是质数。
AC代码如下,时间复杂度为:
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
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/17457864.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
2022-06-05 无线网络