题解
题目大意,一艘船在海上受风力移动,给出每秒的风向,船每秒也可以自己动1格,问到达终点的最短时间
使用二分答案求解,check时按照风向走mid次,最后计算所处位置到达终点的曼哈顿距离是否小于mid(表示mid秒船自己移动机会使用最合理的方式安排)。
由于答案可能很大直接模拟走mid次会超时,将mid是n的整数倍部分直接移动再将余下的模拟移动。
AC代码
#include <stdio.h>
#include <bits/stdc++.h>
#define fst first
#define sed second
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int MAXN = 2e5 + 10;
char s[MAXN];
ll sx, sy, tx, ty, n;
inline void move(char c, ll &x, ll &y, ll k) //将坐标移动k次
{
if (c == 'U') y += k;
if (c == 'D') y -= k;
if (c == 'L') x -= k;
if (c == 'R') x += k;
}
bool check(ll m)
{
ll x = sx, y = sy;
ll k = m / n; //走k轮
for (int i = 0; i < n; i++)
move(s[i], x, y, k);
k = m % n;
for (int i = 0; i < k; i++)
move(s[i], x, y, 1);
ll res = abs(x - tx) + abs(y - ty);
return res <= m; //合理安排剩下的m次操作是否能到
}
int main()
{
#ifdef LOCAL
freopen("C:/input.txt", "r", stdin);
#endif
cin >> sx >> sy >> tx >> ty >> n;
scanf("%s", s);
ll l = 0, r = LINF, ans = -1;
while (l <= r)
{
ll m = l + r >> 1;
if (check(m))
r = m - 1, ans = m;
else
l = m + 1;
}
cout << ans << endl;
return 0;
}