12503 - Robot Instructions


You have a robot standing on the origin of x axis. The robot will be given some instructions. Your taskis 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 thei-th instruction. It is guaranteed that i is a positiveinteger not greater than the number of instructions before this.

Input 

The first line contains the number of test cases T (T$ \le$100). Each test case begins with an integern(1$ \le$n$ \le$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, therobot 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 


解题思路:本题为模拟题,只要用数组记录每一步的走向情况即可,后面直接用就行了,对于位置,直接加上当前移动情况。



#include<stdio.h> #include<string.h> int main() {     int t,n,x,sum;     int a[105];     char c[10];     scanf("%d",&t);     while(t--)     {         sum=0;         scanf("%d",&n);         for(int i=1;i<=n;i++)         {             scanf("%s",c);             if(!strcmp(c,"LEFT"))   //命令处理,向左走                 a[i]=-1;             else if(!strcmp(c,"RIGHT"))//命令处理,向右走                 a[i]=1;             else   //第3种命令             {                 scanf("%s",c);   //吸收as                 scanf("%d",&x);                 a[i]=a[x];             }             sum+=a[i];         }         printf("%d\n",sum);     }     return 0; }