有一辆智能小车,最初(时间为0)的位置为(0,0),我们想知道它最后的位置。小车以每小时10公里的速度向北移动(以北为y轴正向,以东为x轴正向)。小车会受到一系列依照时间戳记排序的命令,1表示“向左转”,2表示“向右转”,3表“停止”。每个命令的前面有一个时间戳记,所以我们知道该命令是何时发出的。最后一个命令一定是“停止”。我们另外假设,这辆小车非常灵活,它可以在瞬间转弯。
以下列输入为例。小车在时间为5的时候收到一个“向左转”的命令1,在时间10收到一个“向右转”的命令2,在时间15收到一个“停止”的命令3。那么在最后时间15的时候,小车的位置将在(-50,100)。程序只要求输出小车最后的位置,第一个整数是x坐标,第二个整数是y坐标。
输入
输入包含多个命令,每个命令由整数time和command组成,表示在时刻time发出命令command。command的取值范围1-3,含义如上所述。
输出
输出占一行,包含两个整数,表示小车的最终位置。两个整数之间由空格隔开。
样例输入 Copy
5
1
10
2
15
3
样例输出 Copy
-50 100
源码:
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
struct Command
{
int flag;
int time;
Command* next;
};
int main() {
int x, y;
x = 0;
y = 0;
int time = 0;
int diection = 0; //北,逆时针相加1东,2南,3西
int speed = 10;
int input_flag=0;
int input_time=0;
Command* head;
Command* n;
Command* t;
n = new Command();
n->flag = input_flag;
n->time = input_time;
t = n;
head = n;
int i = 0;
while (input_flag!=3) {
cin >> input_time;
cin >> input_flag;
n = new Command();
n->time = input_time;
n->flag = input_flag;
t->next = n;
t = t->next;
}
while (head!=nullptr)
{
switch (diection)
{
case 0:
y += 10 * time;
break;
case 1:
x += 10 * time * -1;
break;
case 2:
y += 10 * time * -1;
break;
case 3:
x += 10 * time;
break;
}
if (head->flag == 1) {
diection = diection + 1;
if (diection == 4) {
diection = 0;
}
}
else if (head->flag == 2)
{
diection = diection - 1;
if (diection == -1) {
diection = 3;
}
}
if (head->next != nullptr)
{
time = head->next->time - head->time;
}
head = head->next;
}
cout << x << " " << y;
}