比赛 2025暑期集训第7场 评测结果 WWWWWWWWWA
题目名称 填数 最终得分 10
用户昵称 会挽弯弓满月 运行时间 0.027 s
代码语言 C++ 内存使用 3.78 MiB
提交时间 2025-08-11 15:22:51
显示代码纯文本
#include <bits/stdc++.h> 
using namespace std;
const int N=15,M=1000;
int read(){
	int x=0,f=1;
	char c=getchar();
	while(c<48||c>57){
		if(x==45) f=-1;
		c=getchar();
	}
	while(c>=48&&c<=57){
		x=x*10+c-48;
		c=getchar();
	}
	return f*x;
}
int n,m;
int s[N][N];
bool vis[M];
bool st[M];
int pri[M],tot;
void phi(){
	memset(st,1,sizeof(st));
	st[0]=st[1]=0;
	for(int i=2;i<=M;i++){
		if(st[i]) pri[++tot]=i;
		for(int j=1;j<=tot&&pri[j]*i<=M;j++){
			st[pri[j]*i]=0;
			if(i%pri[j]==0) break;
		}
	}
	return;
}
bool edge(int x,int y){
	if(x<1||x>n) return 0;
	if(y<1||y>n) return 0;
	return 1;
}
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
//行 列 
bool dfs(int h,int w,int cnt){
	if(cnt==m) return 1;
	if(h==n+1) return 0;
	if(w==n+1) return dfs(h+1,1,cnt);
	int tw,th;
	bool flag;
	for(int i=2;i<=m;i++){
		if(vis[i]) continue;
		flag=1;
		for(int j=0;j<4;j++){
			tw=w+dx[j];th=h+dy[j];
			if(!edge(th,tw)) continue;
			if(!s[th][tw]) continue;
			if(!st[s[th][tw]+i]){
				flag=0;
				break;
			}
		}
		if(flag){
			vis[i]=1;
			s[h][w]=i;
			if(dfs(h,w+1,cnt+1)) return 1;
		}
	}
	return 0;
}
int main(){
	freopen("tianshu.in","r",stdin);
	freopen("tianshu.out","w",stdout);
	n=read();
	m=n*n;
	phi();
	s[1][1]=1;
	if(dfs(1,2,1)){
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++)
				printf("%d ",s[i][j]);
			putchar('\n');
		}
	}
	else printf("-1");
	return 0;
}