CSU1112

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010992313/article/details/70197445

CSU1112:机器人指令

Description

数轴原点有一个机器人。该机器人将执行一系列指令,你的任务是预测所有指令执行完毕之后它的位置。

·LEFT:往左移动一个单位

·RIGHT: 往右移动一个单位

·SAME AS i: 和第i 条执行相同的动作。输入保证i 是一个正整数,且不超过之前执行指令数

Input

输入第一行为数据组数T (T<=100)。每组数据第一行为整数n (1<=n<=100),即指令条数。以下每行一条指令。指令按照输入顺序编号为1~n。

Output

对于每组数据,输出机器人的最终位置。每处理完一组数据,机器人应复位到数轴原点。

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

主要考虑对“SAME AS 1”这种字符输入的处理。

把“SAME”“AS”“1”分为三个输入,in.next()in.next() in.nextInt()

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		int T = in.nextInt();
		for(int t=0;t<T;t++)
		{
			int n = in.nextInt();
			//位置
			int pos = 0;
			//behave存储每一步动作
			int[] behave = new int[n];
			for(int i=0;i<n;i++)
			{
				String input = in.next();
				switch(input)
				{
				case "LEFT":
					pos--;
					behave[i] = -1;
					break;
				case "RIGHT":
					pos++;
					behave[i] = 1;
					break;
				default:
					//a读入“AS”(不做任何事,只读入),k读入最后的数字
					String a = in.next();
					int k = in.nextInt();
					//更新相应behave
					behave[i] = behave[k-1];
					//更新位置
					pos = pos+behave[k-1];
				}
			}
			System.out.println(pos);
		}
		in.close();
	}

}


猜你喜欢

转载自blog.csdn.net/u010992313/article/details/70197445
今日推荐