2013-05-28 23:06:47Morris
[UVA] 12503 - Robot Instructions
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, 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![$ le$](http://uva.onlinejudge.org/external/125/12503img1.png)
![$ le$](http://uva.onlinejudge.org/external/125/12503img1.png)
![$ le$](http://uva.onlinejudge.org/external/125/12503img1.png)
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
Problemsetter: Rujia Liu, Special Thanks: Feng Chen, Md. Mahbubul Hasan
#include <stdio.h>
int main() {
scanf("%*d");
char cmd[30];
int n, I[105], i, j;
while(scanf("%d ", &n) == 1) {
int x = 0;
for(i = 0; i < n; i++) {
gets(cmd);
if(cmd[0] == 'L')
I[i] = -1, x--;
else if(cmd[0] == 'R')
I[i] = 1, x++;
else {
sscanf(cmd+8, "%d", &j);
I[i] = I[j-1], x += I[i];
}
}
printf("%d\n", x);
}
return 0;
}