Happy Robot
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 147 Solved: 68
[ Submit][ Status][ Web Board]
Description
Input
There will be at most 1000 test cases. Each case contains a command sequence with no more than 1000 characters.
Output
For each test case, print the case number, followed by minimal/maximal possible x (in this order), then the minimal/maximal possible y.
Sample Input
F?F
L??
LFFFRF
Sample Output
Case 1: 1 3 -1 1
Case 2: -1 1 0 2
Case 3: 1 1 3 3
机器人执行指令,可以前进,左转,右转。
主要是对 ‘?’ 特殊处理
结构体DP[ d ][ i ] 保存当前方向为DIRS[ d ] ,剩下 i 个指令要执行,所取得的X,Y的最大最小值。
#include <cstdio>
#include <cstring>
#include <cassert>
#include <cstdlib>
#include <iostream>
using namespace std;
struct Point
{
int x, y;
Point(int x = 0, int y = 0) : x(x), y(y) {}
};
typedef Point Vector;
const int MAXN = 1000 + 5;
char CMD[MAXN];
Vector DIRS[4];
int n;
void init()
{
DIRS[0].x = 1; //向右
DIRS[0].y = 0;
DIRS[1].x = 0; //向上
DIRS[1].y = 1;
DIRS[2].x = -1; //向左
DIRS[2].y = 0;
DIRS[3].x = 0; //向下
DIRS[3].y = -1;
}
struct Ans
{
int minX, minY, maxX, maxY;
Ans& update(const Ans& a) //更新X,Y的最大,最小值
{
minX = min(minX, a.minX);
minY = min(minY, a.minY);
maxX = max(maxX, a.maxX);
maxY = max(maxY, a.maxY);
return *this;
}
Ans operator + (const Vector& v) const //重载“+”运算符
{
Ans a = *this;
a.minX += v.x;
a.maxX += v.x;
a.minY += v.y;
a.maxY += v.y;
return a;
}
};
// DP(d, i) 表示当前方向为DIRS中的(0,1,2,3),剩下i个指令要执行,X,Y分别能走出的差量
Ans DP[4][MAXN];
int main()
{
//freopen("in.txt", "r", stdin);
init();
for (int t = 1; scanf("%s", &CMD) == 1; t++)
{
n = strlen(CMD);
memset(DP, 0, sizeof(DP));
for (int i = 1; i <= n; i++) // 还剩i个指令
{
char c = CMD[n - i];
for (int d = 0; d < 4; d++) // 当前的方向
{
Ans& a = DP[d][i];
Ans al = DP[(d + 1) % 4][i - 1], //上一个指令,左转
ar = DP[(d - 1 + 4) % 4][i - 1], //上一个指令,右转
af = DP[d][i - 1] + DIRS[d]; //上一个指令,前进
if (c == 'L') a = al; //判断是什么指令
else if (c == 'R') a = ar;
else if (c == 'F') a = af;
else
{
assert(c == '?'); //如果是‘?’
a = al.update(ar).update(af); //更新最值
}
}
}
Ans& a = DP[0][n];
printf("Case %d: %d %d %d %d\n", t, a.minX, a.maxX, a.minY, a.maxY);
}
return 0;
}