CF - Magic Ship (二分)

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;
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值