计蒜课 机器人

蒜头君收到了一份礼物,是一个最新版的机器人。

这个机器人有 4 4 种指令:

  1. forward x,前进 x x 米。
  2. back x,先向后转,然后前进 x x 米。
  3. left x,先向左转,然后前进 x x 米。
  4. right x,先向右转,然后前进 x x 米。

现在把机器人放在坐标轴原点,起始朝向为 x x 轴正方向。

经过一系列指令以后,你能告诉蒜头君机器人的坐标位置吗。

坐标轴上一个单位长度表示 1 1 米。

1547060054324

输入格式

第一行输入一个整数 n ( 1 n 100 ) n(1 \le n \le 100) 表示指令的个数。

接下里 n n 行,每行输入形如上面的指令,其中 1000 x 1000 -1000 \le x \le 1000

输出格式

输出两个整数 x , y x,y 表示机器人最后坐标。

用空格隔开。

样例输入

10

back -9

left 3

left 8

back 15

right 10

right -7

right -3

left 11

right 17

left 3

样例输出

9 -7

#include <iostream> 
#include<string>
using namespace std;
int main() {
	string direction;
	int n,distance;
	cin>>n;
	int x=0,y=0;
	//true 为此时正对的方向
	bool up=false;  //向上
	bool down=false;  //向下
	bool left=false;  //向左
	bool right=true;  //向右   
	for(int i=0;i<n;i++)
	{
		cin>>direction>>distance;
		if(direction=="forward")
		{
			if(up==true)
			{
				y=y+distance;
			}
			else if(down==true)
			{
				y=y-distance;
			}
			else if(right==true)
			{
				x=x+distance;
			}
			else
			{
				x=x-distance;
			}	
		}
		else if(direction=="back")
		{
			if(up==true)
			{
				up=false;
				down=true;
				y=y-distance;
			}
			else if(down==true)
			{
				down=false;
				up=true;
				y=y+distance;
			}
			else if(right==true)
			{
				right=false;
				left=true;
				x=x-distance;
			}
			else
			{
				left=false;
				right=true;
				x=x+distance;
			}
		}
		else if(direction=="right")
		{
			if(up==true)
			{
				up=false;
				right=true;
				x=x+distance;
			}
			else if(down==true)
			{
				down=false;
				left=true;
				x=x-distance;
			}
			else if(right==true)
			{
				right=false;
				down=true;
				y=y-distance;
			}
			else
			{
				left=false;
				up=true;
				y=y+distance;
			}
		}
		else
		{
			if(up==true)
			{
				up=false;
				left=true;
				x=x-distance;
			}
			else if(down==true)
			{
				down=false;
				right=true;
				x=x+distance;
			}
			else if(right==true)
			{
				right=false;
				up=true;
				y=y+distance;
			}
			else
			{
				left=false;
				down=true;
				y=y-distance;
			}
		}
	}
	cout<<x<<" "<<y<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wait_13/article/details/86500628