# UVA 12503 - Robot Instructions ### Sample Input: 1. 第一行代表有幾組 test cases (變數 c) 2. 每組測資的第一行代表有幾個 instructions (變數 n) 3. 接下來的 n 行,每一行代表一個 instruction **Instruction:** * LEFT: 往左走一格 * RIGHT: 往右走一格 * SAME AS i: 和第 i 個 instruction 一樣 (i 從 1 開始) ```= 2 3 LEFT RIGHT SAME AS 2 5 LEFT SAME AS 1 SAME AS 2 SAME AS 1 SAME AS 4 ``` ### Sample Output: 每一組 test case 輸出 robot 最後的位置 (初始位置為 0) ```= 1 -5 ``` ### 程式碼: ```cpp= #include <iostream> #include <string> #include <sstream> #include <map> #define haku author using namespace std; int main() { string str; int c, n; getline(cin, str); c = stoi(str); // 輸入 test case 數量 (c) while (c--) { getline(cin, str); n = stoi(str); // 輸入 instruction 數量 (n) int pos = 0; // robot 最初的位置 map<int, int> ins; // 儲存 instruction,用來查找 Same as i for (int i = 1; i <= n; i++) { getline(cin, str); // 輸入 instruction if (str[0] == 'L') { // 輸入為 "LEFT" 時: pos--; ins.insert({ i, -1 }); } else if (str[0] == 'R') { // 輸入為 "RIGHT" 時: pos++; ins.insert({ i, 1 }); } else if (str[0] == 'S') { // 輸入為 "SAME AS i" 時: int tmp; string garb; stringstream ss(str); ss >> garb >> garb >> tmp; // 只會用到最後一個數字,所以前面的 "SAME AS" 丟掉 pos += ins[tmp]; // 查找存在 map 裡的 instruction & 執行動作 ins.insert({ i, ins[tmp] }); // 這裡一樣要存入 map } } cout << pos << endl; // 輸出位置 } return 0; } ```
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.