Robot Instructions
Robot Instructions |
You have a robot standing on the origin of x axis. The robot will be given some instructions. Your task is to predict its position after executing all the instructions.
- LEFT: move one unit left (decrease p by 1, wherep is the position of the robot before moving)
- RIGHT: move one unit right (increase p by 1)
- SAME AS i: perform the same action as in thei-th instruction. It is guaranteed that
i is a positive integer not greater than the number of instructions before this.
Input
The first line contains the number of test cases T (T100). Each
test case begins with an integer n (
1n100),
the number of instructions. Each of the following n lines contains an instruction.
Output
For each test case, print the final position of the robot. Note that after processing each test case, the robot should be reset to the origin.
Sample Input
2 3 LEFT RIGHT SAME AS 2 5 LEFT SAME AS 1 SAME AS 2 SAME AS 1 SAME AS 4
Sample Output
1 -5
题解
题目意思是说,给一个机器人指令,完事输出最终的坐标。直接模拟即可,没什么大问题。
代码示例
/**** *@PoloShen *Title:B */ #include <iostream> #include <string> #include <vector> using namespace std; void solve(){ int n; cin >> n; vector<int> command; int pos = 0; string inp; int i = 0; while (n--){ cin >> inp; if (inp[0] == 'L'){ command.push_back(-1); pos += -1; } else if (inp[0] == 'R'){ command.push_back(1); pos += 1; } else if (inp[0] == 'S'){ cin >> inp; int tmp; cin >> tmp; pos += command[tmp-1]; command.push_back(command[tmp-1]); } } cout << pos << endl; } int main(){ int T; cin >> T; while (T--) solve(); return 0; }