C. Magic Ship
题意:
输入
(
x
1
,
y
1
)
,
(
x
2
,
y
2
)
(
1
e
9
)
(x1,y1),(x2,y2)(1e9)
(x1,y1),(x2,y2)(1e9),表示两个点;
输入
n
(
1
e
5
)
n(1e5)
n(1e5),接下来输入长度为
n
n
n的字符串,由
U
D
L
R
UDLR
UDLR表示风吹的方向,船也可以自己动,问最短在多长时间使船从
(
x
1
,
y
1
)
(x1,y1)
(x1,y1)到
(
x
2
,
y
2
)
(x2,y2)
(x2,y2)。
题解:
此题的难点在于很难想到二分,其实从反方向来考虑,很容易就可以得到,当船在 t t t时刻可以到达目的地,那么以后的任意时刻都可以保持(只要往风反方向开就可以了)。
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int dx,dy;
const int N=2e5+9;
int n;string s;
#define P pair<int,int>
P a[N];
int sx,sy,tx,ty;
bool check(ll x){
ll res=x%n,y=x/n;
ll dx,dy;
dx=1ll*y*a[n].first+a[res].first;
dy=1ll*y*a[n].second+a[res].second;
return abs(tx-sx-dx)+abs(ty-sy-dy)<=x;
}
int main(){
// freopen("tt.in","r",stdin),freopen("tt.out","w",stdout);
cin>>sx>>sy>>tx>>ty>>n;
cin>>s;s=" "+s;
for(int i=1;i<=n;i++){
a[i]=a[i-1];
if(s[i]=='U')a[i].second++;
if(s[i]=='D')a[i].second--;
if(s[i]=='L')a[i].first--;
if(s[i]=='R')a[i].first++;
}
ll l=0,r=1e18,mid,ans=-1;
while(l<=r){
mid=(l+r)>>1;
if(check(mid))ans=mid,r=mid-1;
else l=mid+1;
}
cout<<ans<<endl;
return 0;
}