codeforces contest 1117 C. Magic Ship---二分

题目链接:https://codeforces.com/problemset/problem/1117/C

题解:二分天数可解该题,主要是要考虑的曼哈顿距离的性质,风带来的影响是不能改变的,所以可以预处理出风带来的距离改变,在此基础上判断能否在k天内走到终点

#include
#define ll long long
using namespace std;
const int maxn = 1e5+5;

struct node{
    ll x, y;
    node(){
        x = y = 0;
    }
}d[maxn], st, ed;

int n;

bool check(ll k){
    ll t1 = k/n;
    ll t2 = k%n;
    node res;
    res.x += st.x + d[n-1].x * t1;
    res.y += st.y + d[n-1].y * t1;
    if(t2 != 0){
        res.x += d[t2-1].x;
        res.y += d[t2-1].y;
    }
    if(abs(ed.x - res.x) + abs(ed.y - res.y) <= k) return true;
    else return false;
}

int main(){
    cin >> st.x >> st.y >> ed.x >> ed.y;
    cin >> n;
    string s;
    cin >> s;
    memset(d, 0, sizeof d);
    for(int i = 0; i < n; i++){
        if(i > 0) d[i] = d[i-1];
        if(s[i] == 'U') d[i].y++;
        if(s[i] == 'D') d[i].y--;
        if(s[i] == 'R') d[i].x++;
        if(s[i] == 'L') d[i].x--;
    }
    ll l = 1, r = 1e15, mid;
    while(l < r){
        mid = (l+r)/2;
        if(check(mid)) r = mid;
        else l = mid + 1;
    }
    if(!check(l)) cout << "-1\n";
    else cout << l << endl;
    return 0;
}

你可能感兴趣的:(思维)