From 5629193e2e883cbde6d5075d303cd810d735579d Mon Sep 17 00:00:00 2001 From: visitworld <745350128@qq.com> Date: Sun, 6 Nov 2016 13:16:39 +0800 Subject: [PATCH] Add files via upload --- lx.cpp | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++ solution.md | 19 +++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 lx.cpp diff --git a/lx.cpp b/lx.cpp new file mode 100644 index 00000000..dd2a7642 --- /dev/null +++ b/lx.cpp @@ -0,0 +1,68 @@ +#include + +#define rep(i, x, y) for (int i = (x), _ = (y); i <= _; ++i) +#define down(i, x, y) for (int i = (x), _ = (y); i >= _; --i) +#define x first +#define y second +#define LX_JUDGE + +using namespace std; +typedef long long LL; + +const int inf = 0x3f3f3f3f; +const int N = 1e5 + 10; + +const int dx[] = {1, 0, -1, 0}; +const int dy[] = {0, -1, 0, 1}; + +typedef pair point; + +inline point operator + (const point & a, const point & b) //位移向量相加 +{ + return point(a.x + b.x, a.y + b.y); +} + +inline point rotate(point x, int d) //逆时针旋转移动向量 90*d 度 +{ + if (!d) + return x; + return rotate(point(x.y, -x.x), d - 1); +} + +class RobotHerb +{ +public: + LL getdist(int T, vector a) + { + point ans(0, 0); + point p(0, 0), q(0, 0); + int dir = 0; + + rep (i, 0, a.size() - 1) //模拟一次命令序列的执行 + { + q.x += a[i] * dx[dir]; + q.y += a[i] * dy[dir]; + dir = (dir + a[i]) % 4; + } + + int cnt = T / 4; //把 T 次命令分为 (T/4)*4 次和零散部分 + T %= 4; + + rep (i, 0, 3) + { + p = p + q; + q = rotate(q, dir); + } + + ans = point(p.x * cnt, p.y * cnt); + + rep (i, 1, T) //计算零散部分 + { + ans = ans + q; + q = rotate(q, dir); + } + + return abs(ans.x) + abs(ans.y); + } +}; + diff --git a/solution.md b/solution.md index e69de29b..821291be 100644 --- a/solution.md +++ b/solution.md @@ -0,0 +1,19 @@ +###SRM570 div1 250 + +作者:吕欣 +关键词:模拟,找规律 + +###题意简述 + +某机器人在平面上原点处,它有一个长度为 $$n(\leq50)$$ 的命令序列,其中第 $$i$$ 个命令中它会向当前方向移动 $$a[i]$$ 个位置,然后顺时针旋转 + $$a[i]\times 90$$ 度,它会重复执行这个命令序列 $$T$$ 次,求它最后停下来的位置和原点的曼哈顿距离。 + +约定:$$T, a[i]\leq10^9, n\leq 50$$ + +###算法分析 + +不难发现,无论机器人执行一次命令序列之后方向如何旋转,它重复执行 $$4$$ 次命令序列之后总能回到原来的方向,所以每 $$4$$ 次命令序列使它产生的位移是相同的。 + +我们暴力模拟 $$4$$ 次命令序列,就能知道 $$4\times\lfloor{\frac T4}\rfloor$$ 次命令序列的执行使它产生的位移,同时它现在恢复了初始的朝向,我们对 $$T\mod 4$$ 的零散部分再模拟一遍即可得到它最终的的位置 $$(x,y)$$,答案即为 $$\left| x\right|+\left|y\right|$$。 + +时间复杂度 $$O(n)$$,空间复杂度 $$O(1)$$