可以将两个政党的议员交叉放,就可以避免相邻。就像这样:
1 0 1 0 1 0
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
1 0 1 0 1 0
代码为了方便读懂写了点注释:
(写的有点丑)
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n,a,b,k;
ll d[105];
int main(){
cin>>n>>a>>b;
if(a*b<n){
cout<<"-1";//判断是否无法满足要求
return 0;
}
if(a&1){//如果每行长度是奇数,那么从小到大输出
for(int i=1;i<=a;i++){
for(int j=1;j<=b;j++){
if(k<=n) cout<<++k<<' ';
else cout<<"0 ";
}
cout<<'\n';
}
}else{//如果每行长度是偶数
for(int i=1;i<=a;i++){
if(i&1){//第奇数行从小到大
for(int j=1;j<=b;j++){
if(k+1<=n) cout<<++k<<' ';
else cout<<"0 ";
}
}else{//偶数行从大到小
memset(d,0,sizeof(d));//因为要判断当前已确定位置的数量是否大于n,所以用一个数组存一下要输出的
for(int j=b;j>=1;j--){
if(k+1<=n) d[j]=++k;
else break;
}
for(int j=1;j<=b;j++) cout<<d[j]<<' ';
}
cout<<'\n';
}
}
return 0;
}