UVA12503 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 ≤ 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值