CF - Magic Ship (二分)
题目链接: Educational Codeforces Round 60 (Rated for Div. 2) Magic Ship
题意
给你一个起始点(sx,sy),要求到达(ex,ey),再给你一个长度为n字符串s1,s1中包含四个字母,U,D,L,R,分别代表上下左右,代表每个时刻的风向,并且这个风向是循环的(也就是字符串到达末尾时回到第一个字符)。你每次可以选择上下左右或者不动(每次移动一步)。问最快什么时候能到达终点。
数据范围
$ 0 < sx , sy , ex , ey < 10^9 $ ,$ n < 10^5 $
思路
说来惭愧,再看到了最快后,我想到了二分,但是因为随时间变化的坐标,不是单调的,我就排除了这一假设。
我们只需转换一下思路,如果当前能到达这个点,那么以后的点都能到,因为,在到了这个点后,我们只需每次都向风的反方向移动就行了。
代码
#include <bits/stdc++.h>
using namespace std;
#define rep(i,j,k) for(int i = (int)j;i <= (int)k;i ++)
#define debug(x) cerr<<#x<<":"<<x<<endl
#define pb push_back
typedef long long ll;
const int MAXN = (int)1e6+7;
ll a[MAXN];
ll sx,sy,ex,ey,n;
ll diX,diY;
ll tx,ty;
char op[MAXN];
void go(ll &x,ll &y,char ch) {
if (ch == 'U') {
y += 1;
}else if (ch == 'D') {
y -= 1;
}else if (ch == 'L') {
x -= 1;
}else if (ch == 'R') {
x += 1;
}
}
bool OK(ll m) {
ll chg = abs(diX-m*tx)+abs(diY-m*ty);
if (chg > m*n) return false;
return true;
}
int main()
{
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin >> sx >> sy >> ex >> ey;
diX = ex-sx;
diY = ey-sy;
cin >> n;
cin >> op+1;
tx=0,ty=0;
rep(i,1,n) {
go(tx,ty,op[i]);
}
ll l = 0,r = 2e9+4;
while (l <= r) {
ll m = l+r>>1;
if (OK(m)) r = m-1;
else l = m+1;
}
if (l == 2e9+5) {
cout << -1 << endl;
return 0;
}
tx *= r;
ty *= r;
rep(i,1,n) {
go(tx,ty,op[i]);
if (abs(diX-tx)+abs(diY-ty)<=i+n*r) {
cout << i+n*r << endl;
break;
}
}
}