跳到正文

个人记录

B3738 [信息与未来 2018] 素数方阵 题解

Nodellaspkl约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

题目传送门

分析题意

这道题其实就是素数表和蛇形方阵的结合版,比较简单,模拟一下就能通过。

解题思路

对于蛇形方阵可以建立方向数组dx和dy,每次碰到有数字的方阵格子就会让方向变量自增一,作为转向。素数表可以使用O(nn)\text{O}(n\sqrt{n})的方法暴力求解。

AC code\texttt{AC code}

C++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int prime[405];
int sq[25][25];
int cur = 0;

const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};

bool isP(int x)
{
	for(int i = 2; i * i <= x; i++)
	{
		if(x % i == 0) return 0;
	}
	return 1;
}

int main()
{
	for(int i = 2; i <= 3000; i++)
	{
		if(isP(i))
		{
			prime[++cur] = i;
		}
	}
	int n, x, y;
	cin >> n >> x >> y;
	int dir = 0;
	int tx = 1, ty = 1;
	for(int i = 1; i <= n * n; i++)
	{
		sq[tx][ty] = prime[i];
		//cout << tx << " " << ty << " " << prime[i] << endl;
		tx += dx[dir];
		ty += dy[dir];
		if(sq[tx][ty] || tx > n || tx < 1 || ty > n || ty < 1)
		{
			tx -= dx[dir];
			ty -= dy[dir];
			dir++;
			dir %= 4;
			tx += dx[dir];
			ty += dy[dir];
		}
	}
	cout << sq[x][y];
	return 0;
}
原文