P14942 解题报告

· · 题解

构造半天。

当 k\le \lfloor\frac{n}{2}\rfloor 时,无解,因为任何一个数的出现次数不会超过 2n-1。

难点在于构造。

发现当 k> \lfloor\frac{n}{2}\rfloor 可以先填上 1\sim \lfloor\frac{n}{2}\rfloor+1,剩下的随机即可。现在我们考虑填上 1\sim \lfloor\frac{n}{2}\rfloor+1 的构造方法。

当 n 为偶数时,以 6 为例子,此时 k 不能小于 4。可以这样填:

?????4
?????4
?????4
?????4
?????4
444444

这样就转化为了 n=5 的子问题。因此考虑构造奇数。

斜线分组,考虑分成 2n-1 组。填入 1,2,2,3,3,...,\lfloor\frac{n}{2}\rfloor+1,\lfloor\frac{n}{2}\rfloor+1,1,1,2,2,...,\lfloor\frac{n}{2}\rfloor,\lfloor\frac{n}{2}\rfloor。

举个例子,当 n=9 时构造如下:

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';
        }
    }
}