a452簡單相鄰差分・曼哈頓距離
APCS 2022/10:巴士站牌 (ZeroJudge i428)
計算每對相鄰站點的水平與垂直距離,維護最大及最小值。
這題在學什麼
從 (x1,y1) 到 (x2,y2) 的行進時間是 |x1-x2|+|y1-y2|。只比較原路線相鄰的站點,因此 n 個站點恰有 n-1 段要處理。
讀入下一站時,利用上一站座標求距離,再更新最大與最小值。完成後把下一站保存為上一站,繼續讀下一筆即可,不需要排序座標或枚舉所有點對。
Step-by-step animation
範例的三段距離
步驟 1 / 3
第一段
(1,1)→(1,3) 的距離為 0+2=2,先初始化 min 與 max。
(1,1)
(1,3)
(4,5)
(2,6)
- distance
- 2
- min / max
- 2 / 2
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, x, y; cin >> n >> x >> y;
int low = INT_MAX, high = 0;
for (int i = 1; i < n; ++i) {
int nx, ny; cin >> nx >> ny;
int d = abs(nx-x) + abs(ny-y);
low = min(low, d); high = max(high, d);
x = nx; y = ny;
}
cout << high << ' ' << low << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。