题意:题目已经概括的很清楚了。
思路:
通过枚举,我们可以发现有 5 种情况一定无解:
| 情况 \ m 或 n |
m |
n |
| 1 |
1 |
2 |
| 2 |
1 |
3 |
| 3 |
2 |
1 |
| 4 |
2 |
2 |
| 5 |
3 |
1 |
不难发现,在这些情况下的 m+n<5。
if(m+n<5)cout<<-1;
对于 n=1 且 m=1 的情况,输出 1。
if(m==1&&n==1){
cout<<1;
return 0;
}
对于其他情况,可以分段编数:
对于 0≤i≤m,0≤j≤n,
-
若 i+jmod2=0,将其顺序在 [0,2m×n] 区间内编数。
-
若 i+jmod2=1,将其顺序在 [2m×n+1,m×n] 区间内编数。
例:n=6,m=5
| n \ m |
1 |
2 |
3 |
4 |
5 |
| 1 |
1 |
16 |
2 |
17 |
3 |
| 2 |
18 |
4 |
19 |
5 |
20 |
| 3 |
6 |
21 |
7 |
22 |
8 |
| 4 |
23 |
9 |
24 |
10 |
25 |
| 5 |
11 |
26 |
12 |
27 |
13 |
| 6 |
28 |
14 |
29 |
15 |
30 |
其中,绿色 部分为 [0,2m×n] 区间,棕色 部分为 [2m×n+1,m×n] 区间。
根据实验,此方法可行。
#include<bits/stdc++.h>
using namespace std;
int a[101][101];
int main(){
int m,n;
cin>>m>>n;
if(m==1&&n==1){
cout<<1;
return 0;
}
if(m+n<5)cout<<-1;
else{
int t=1,q=(m*n)/2+1,cnt=0;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
cnt++;
if((i+j)%2)cout<<t++;
else cout<<q++;
cout<<' ';
}
}
}
return 0;
}