跳到正文

题解

P14942 解题报告

mo_mo_yu0_0约 3 分钟
原文

这是 2026年1月1日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年1月1日
更新
2026年1月1日
篇幅
约 3 分钟
题目
P14942

版本

  1. v2当前
  2. v1

构造半天。

发现 k≤⌊n2⌋k\le \lfloor\frac{n}{2}\rfloor 无解,难点在于构造。

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

当 nn 为偶数时,以 66 为例子,此时 kk 不能小于 44。可以这样填:

代码
?????4
?????4
?????4
?????4
?????4
444444

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

斜线分组,考虑分成 2n−12n-1 组。填入 1,2,2,3,3,...,⌊n2⌋+1,⌊n2⌋+1,1,1,2,2,...,⌊n2⌋,⌊n2⌋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=9n=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

最后随机填数在输出即可。

C++
#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';
		}
	}
}