跳到正文

题解

题解:P14308 【MX-S8-T1】斐波那契螺旋

__coool__约 4 分钟
原文

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

文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月1日
篇幅
约 4 分钟
题目
P14308

版本

  1. v2当前
  2. v1

题解:P14308 【MX-S8-T1】斐波那契螺旋

一道比较水的模拟/枚举题。我的解法应该是最好想的做法之一,赛时不到五分钟就想到然后就直接打了,如果有更好的解法欢迎讨论。

分析 & 思路导引

先预处理出斐波那契数组 fif_i,观察到数据最大不过是 101810^{18},而 1018≤f8810^{18} \leq f_{88} ,于是我们判断出这题可以枚举预处理出每个正方形的左下角坐标 (x1,y1)(x_1,y_1) 和右上角坐标 (x2,y2)(x_2,y_2)。又因为正方形边长为 fif_i,所以我们可以推出正方形个数不超过 8888 个。在如此小的数据规模下完全可以在线查询(每次枚举坐标看是否符合条件即可)。

具体实现

给出查询的坐标 (x0,y0)(x_0,y_0),我们只需枚举每一个正方形,拿 (x0,y0)(x_0,y_0) 和正方形左下角和右上角坐标进行比较,

如果满足:

{x1≤x0≤x2y1≤y0≤y2\begin{cases}{ \\x_1 \leq x_0 \leq x_2} \\y_1 \leq y_0 \leq y_2 \end{cases}

输出答案即可。

又因为在边界上时让我们输出最小的正方形边长,因此我们只需从小到大枚举正方形即可,第一个满足条件的正方形一定是边长小的,至此解答结束。

参考代码

C++
#include <bits/stdc++.h>
#define cin  std::cin
#define cout std::cout
#define int long long
bool Mbe;
const int N = 1e6;
int f[105], n, ans = 0;;
struct square {
	int _x1, _y1, _x2, _y2;
} sq[105];

void solve(int xx, int yy) {
	ans = 0;
	for (int i = 1 ; i <= 100; i++) {
		int xx1 = sq[i]._x1, yy1 = sq[i]._y1,
		    xx2 = sq[i]._x2, yy2 = sq[i]._y2;
		if (xx >= xx1 && xx <= xx2 && yy >= yy1 && yy <= yy2) {
			ans = i;
			break;
		}
	}
	cout << f[ans] << '\n';
}

bool Med;
signed main() {
	std::cerr << "Mem: " << (&Med - &Mbe) / 1048576.0 << "MB\n";
	std::ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	f[1] = f[2] = 1;
	for (int i = 3; i <= 105; i++) f[i] = f[i - 1] + f[i - 2];
	int flag = 1; // 1 2 3 4 下右上左
	sq[1] = { -1, 0, 0, 1};
	for (int i = 2; i <= 105; i++) {
		int cx1 = 0, cy1 = 0, cx2 = 0, cy2 = 0;
		int lx1 = sq[i - 1]._x1, ly1 = sq[i - 1]._y1,
		    lx2 = sq[i - 1]._x2, ly2 = sq[i - 1]._y2;
		int cside = f[i];
		if (flag == 1) {
			cx1 = lx1; cy1 = ly1 - cside;
			cx2 = lx1 + cside, cy2 = ly1;
			flag = 2;
		}
		else if (flag == 2) {
			cx1 = lx2, cy1 = ly1;
			cx2 = lx2 + cside, cy2 = ly1 + cside;
			flag = 3;
		}
		else if (flag == 3) {
			cx1 = lx2 - cside, cy1 = ly2;
			cx2 = lx2, cy2 = ly2 + cside;
			flag = 4;
		}
		else if (flag == 4) {
			cx1 = lx1 - cside, cy1 = ly2 - cside;
			cx2 = lx1, cy2 = ly2;
			flag = 1;
		}
		sq[i] = {cx1, cy1, cx2, cy2};
	}
	cin >> n;
	while (n--) {
		int x, y;
		cin >> x >> y;
		solve(x, y);
	}
	std::cerr << "Time: " << double(clock() * 1.0 / CLOCKS_PER_SEC ) << '\n';
	return 0;
}