题目来源:湘潭大学OJ-1227
最近俏智很兴奋,因为他收到了一个礼物,人称智能机器人佩奇,这个机器人很独特,当你给它发指令的时候,它就会按照你给出的指令去执行。看到这样的礼物,俏智乐坏了。于是他给你们出了这样的一道题: 假设在一个XOY坐标的平面上,机器人一开始位于原点,面向Y轴正方向。 机器人可以执行向左转,向右转,向后转,前进四个指令。 指令为1.LEFT:向左转2.RIGHT:向右转3.BACK:向后转4.FORWORD n:向前走n(1≤n≤100)个单位
那么如果俏智给出一个指令序列,你能帮忙求出机器人最终的位置吗?
Input
样例的第一行是一个整数T(T≤20),表示样例的个数。
每个样例的第一行是一个整数N(1≤N≤1,000),表示指令的条数。 以后的N行,每行一条指令。
Output
每个样例输出两个整数,为坐标(x,y),之间用空格隔开。
Sample Input 1
2
4
LEFT
FORWORD 1
RIGHT
FORWORD 1
2
BACK
FORWORD 1
Sample Output 1
-1 1
0 -1
运行截图:
下面是我做题是得到的代码,比较繁琐,后期我再对照网上的方法优化一下,
#include<iostream>
#include<string>
#include<cstring>
#include<sstream>
using namespace std;
char cd(char &f,string& g)
{
if(g=="LEFT")
{
if (f == 'u')f = 'l';
else if (f == 'l')f = 'd';
else if (f == 'd')f = 'r';
else if (f == 'r')f = 'u';
}
else if(g=="BACK")
{
if (f == 'u')f = 'd';
else if (f == 'l')f = 'r';
else if (f == 'd')f = 'u';
else if (f == 'r')f = 'l';
}
else if(g=="RIGHT")
{
if (f == 'u')f = 'r';
else if (f == 'l')f = 'u';
else if (f == 'd')f = 'l';
else if (f == 'r')f = 'd';
}
}
int tr(string g)
{
if (g.length() > 7)
g=g.substr(8);
stringstream sstr(g);
int x;
sstr >> x;
return x;
}
int main(){
int x, y;
string a, b, c, d, e;
a = "LEFT";b = "RIGHT";
c = "BACK";d = "FORWORD";
int N;
x = 0; y = 0;
char f = 'u';
int T;
cin>>T;
while(T--){
cin >> N;
N++;
while (N--){
getline(cin,e);
if (e == a)cd(f,a);
else if (e == b)cd(f,b);
else if (e == c)cd(f,c);
else{
int k1 = e.length();
int k = tr(e);
if (f == 'u')y += k;
else if (f == 'l')x -= k;
else if (f == 'd')y -= k;
else if (f == 'r')x += k;}
}cout << x << " " << y << endl;}
return 0;
}
比较了网上的C语言写的代码,真是感觉语言真是个神奇的事物
#include<bits/stdc++.h>
using namespace std;
int main(){
int t,n;
scanf("%d",&t);
char s[9];
int x,y;
while(t--){
scanf("%d",&n);
int a[4]={0,0,0,0};//四个方向
int z=0;
int l;
for(int i=0;i<n;i++){
scanf("%s",s);
if(s[0]=='L') z=(z+3)%4;
else if(s[0]=='R') z=(z+1)%4;
else if(s[0]=='B') z=(z+2)%4;
else if(s[0]=='F'){
scanf("%d",&l);
a[z]+=l;
}
}
x=a[1]-a[3];
y=a[0]-a[2];
printf("%d %d\n",x,y);
}
return 0;
}