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, where p 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 the i-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 (T ≤ 100). Each test case begins with an integer n (1 ≤ n ≤ 100), 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
问题链接:UVA12503 Robot Instructions
问题简述:(略)
问题分析:
机器人从原点出发,有三种命令,其中2中是向左和向右,另外一种是与第i条相同。给定若干条命令,求最后机器人的位置。
需要一个数组dir[],其dir[i]用来记忆第i条指令,其后的计算就简单了。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的C++语言程序如下:
/* UVA12503 Robot Instructions */
#include <bits/stdc++.h>
using namespace std;
const int N = 100;
int dir[N + 1];
int main()
{
string s;
int t, n, ans, i;
cin >> t;
while(t--) {
cin >> n;
ans = 0;
for(int k = 1; k <= n; k++) {
cin >> s;
if(s[0] == 'L') { // LEFT
ans--;
dir[k] = -1;
} else if(s[0] == 'R') { // RIGHT
ans++;
dir[k] = 1;
} else { // SAME AS i
cin >> s >> i;
ans += (dir[k] = dir[i]);
}
}
cout << ans << endl;
}
return 0;
}