日期:2026年11月13日
ZeroJudge 題目連結:c230.松鼠旅行
解題想法
每組測資第一列為一個整數 $N ~(1 \leq N \leq 10^5)$,代表有 $N$ 棵樹。接下來 $N$ 列,每列有 3 個整數 $x_i, y_i ~(1 \leq x_i, y_i \leq 10^4)$、$h ~(1 \leq h_i \leq 10^5)$,代表第 $i$ 棵樹的位置為 $(x_i, y_i)$、高度為 $h_i$。起點為 $(0, 0)$,終點為 $(10000, 10000)$,這 $N$ 棵樹之中必定有兩棵樹位於起點和終點。路徑上選擇的樹只能離起點越來越遠。找出在路徑上任意兩棵樹最大的下降高度,除了起點、終點之外,其它的樹不一定需要經過。
先讀取 $N$ 棵樹的位置、高度,存入陣列 $trees$,再依照 $x^2 + y^2$ 由小到大排序。定義最大高度 $hmax = trees[0].h$、答案 $ans = 0$。用一個 for 迴圈掃過第 $i$ 到第 $n-1$ 棵樹,先更新 $hmax = max(hmax, trees[i].h)$,再更新 $ans = max(ans, hmax - trees[i].h)$。跑完 for 迴圈之後印出 $ans$。
Python 程式碼
這題的記憶體上限很小,只有 16 MB,用 Python 無法過關,會遇到以下的錯誤訊息。
您的程式被監控系統中斷,可能是程式無法正常結束所導致。
Fatal Python error: init_import_site: Failed to import the site module
Python runtime state: initialized
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
MemoryError
Exited with error status 1
while True:
try:
n = int(input())
except EOFError:
break
trees = [tuple(map(int, input().split())) for _ in range(n)]
trees.sort(key = lambda x : x[0]**2 + x[1]**2)
hmax, ans = trees[0][2], 0
for i in range(1, n):
hmax = max(hmax, trees[i][2])
ans = max(ans, hmax - tree[i][2])
print(ans)
C++ 程式碼
使用時間約為 10 ms,記憶體約為 3.6 MB,通過測試。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct {
int x, y, h;
} Tree;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n;
while(cin >> n) {
vector<Tree> trees (n);
for(int i = 0; i < n; i++) {
cin >> trees[i].x >> trees[i].y >> trees[i].h;
}
sort(trees.begin(), trees.end(), [](const Tree& a, const Tree& b) {
return a.x * a.x + a.y * a.y < b.x * b.x + b.y * b.y;
} );
int hmax = trees[0].h, ans = 0; // 最大高度,答案
for(int i = 1; i < n; i++) {
hmax = max(hmax, trees[i].h);
ans = max(ans, hmax - trees[i].h);
}
cout << ans << "\n"; // ans 是負值
}
return 0;
}
沒有留言:
張貼留言