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 (T100). Each test case begins with an integern(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, therobot should be reset to the origin.
Sample Input
23LEFTRIGHTSAME AS 25LEFTSAME AS 1SAME AS 2SAME AS 1SAME 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;}