CPE 一顆星選集 49 道必考題
題目連結:https://zerojudge.tw/ShowProblem?problemid=e516
內容
有一骰子在四個方向上滾動(東,南,西,北),給定一串指令,求出骰子最終頂部的數字。
開局方向對應數字分別為頂面(1)、北面(2)、西面(3)。
指令 ‘north’ 代表北面變為新的底,頂面變為新的北,依此類推。
輸入第一列 n (n <= 1024)代表測資數,等於0時結束。
範例輸入
1
north
3
north
east
south
0
範例輸出
5
1
想法
先用 map 將方向與數字配對,接著模擬骰子滾動,一次判斷一個指令,依照指令動作,更新各個面之相對應數字,最後的頂面對應數字即為所求。
參考資料:YUI HUANG 演算法學習筆記
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #include <bits/stdc++.h> #define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr) using namespace std;
int main(){ fastio; int n, temp; string s; while(cin >> n && n){ map <string, int> mp; mp["top"] = 1, mp["north"] = 2, mp["west"] = 3; mp["bottom"] = 6, mp["south"] = 5, mp["east"] = 4; while(n--){ cin >> s; if(s == "north"){ temp = mp["top"]; mp["top"] = mp["south"]; mp["south"] = mp["bottom"]; mp["bottom"] = mp["north"]; mp["north"] = temp; } else if(s == "east"){ temp = mp["top"]; mp["top"] = mp["west"]; mp["west"] = mp["bottom"]; mp["bottom"] = mp["east"]; mp["east"] = temp; } else if(s == "west"){ temp = mp["top"]; mp["top"] = mp["east"]; mp["east"] = mp["bottom"]; mp["bottom"] = mp["west"]; mp["west"] = temp; } else { temp = mp["top"]; mp["top"] = mp["north"]; mp["north"] = mp["bottom"]; mp["bottom"] = mp["south"]; mp["south"] = temp; } } cout << mp["top"] << "\n"; } return 0; }
|