构造半天。
发现 无解,难点在于构造。
发现当 可以先填上 ,剩下的随机即可。现在我们考虑填上 的构造方法。
当 为偶数时,以 为例子,此时 不能小于 。可以这样填:
?????4
?????4
?????4
?????4
?????4
444444这样就转化为了 的子问题。因此考虑构造奇数。
斜线分组,考虑分成 组。填入 。
举个例子,当 时构造如下:
1 2 2 3 3 4 4 5 5
2 2 3 3 4 4 5 5 1
2 3 3 4 4 5 5 1 1
3 3 4 4 5 5 1 1 2
3 4 4 5 5 1 1 2 2
4 4 5 5 1 1 2 2 3
4 5 5 1 1 2 2 3 3
5 5 1 1 2 2 3 3 4
5 1 1 2 2 3 3 4 4最后随机填数在输出即可。
#include<bits/stdc++.h>
using namespace std;
const int maxn=510;
int n,k;
int a[maxn][maxn];
int cnt[maxn];
void solve(){
memset(cnt,0,sizeof cnt);
cin>>n>>k;
if(k<=n/2)cout<<"fire big\n";//无解
else{
int p=n/2+1;
bool flag=0;
if(n%2==0){//偶数转化奇数
flag=1;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
a[i][j]=p*(i==n||j==n),cnt[p]+=((i==n||j==n));
p--;
n--;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
int x=i+j;
if(x<=n+1)a[i][j]=(x+1)/2;
else a[i][j]=(x-n)/2;
cnt[a[i][j]]++;
}
}//填数
if(flag)++n;
for(int i=1;i<=k;i++){
if(cnt[i])continue;
int x,y;
x=rand()%n+1,y=rand()%n+1;
while(cnt[a[x][y]]==1)x=rand()%n+1,y=rand()%n+1;
cnt[a[x][y]]--,cnt[i]++;
a[x][y]=i;
}//随机填数
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<a[i][j]<<' ';
}
cout<<'\n';
}
}
}