a457簡單座標差分・方向狀態
APCS 2023/06:路徑偵測 (ZeroJudge k731)
把相鄰座標轉成東西南北方向,再比較方向變化統計轉彎。
這題在學什麼
每一段路只會水平或垂直。比較相鄰座標的 x、y 差,就能把路段分類成東、北、西、南其中一個方向。第一段從原點到第一個座標,題目保證向東。
把方向編成循環順序 E=0、N=1、W=2、S=3。新方向減舊方向後對 4 取模:1 是左轉、3 是右轉、2 是掉頭、0 是直走。
Step-by-step animation
路段方向
步驟 1 / 3
第一段向東
原點 (0,0) 到 (2,0),方向編碼為 E=0。
起點
(2,0)
(2,1)
- 方向
- E
- 左/右/掉頭
- 0/0/0
#include <iostream>
using namespace std;
int direction(int x1, int y1, int x2, int y2) {
if (x2 > x1) return 0; // east
if (y2 > y1) return 1; // north
if (x2 < x1) return 2; // west
return 3; // south
}
int main() {
int n;
cin >> n;
int x = 0, y = 0;
int previous = 0; // first segment is east
int left = 0, right = 0, turnAround = 0;
for (int i = 0; i < n; ++i) {
int nx, ny;
cin >> nx >> ny;
int next = direction(x, y, nx, ny);
int change = (next - previous + 4) % 4;
if (change == 1) ++left;
else if (change == 3) ++right;
else if (change == 2) ++turnAround;
previous = next;
x = nx; y = ny;
}
cout << left << ' ' << right << ' ' << turnAround << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。