题意:给你n个探头,m个要读的轨道,n个探头的初始位置是h1---hn(从小到大),m个轨道的位置为p1------pn(也是从小到大),探头可以左移或右移,这些探头可以一起动,每移动一格的时间为1,探头读轨道不计时间,如果要读的轨道上就有探头那么就不需要时间,找最小的时间来读完这些轨道。
思路:(为节省时间就不翻译了)
Let's search the answer
t
with the binary search. Fix some value of
t
. Look at the first head from the left
h
[
i
]
that can read track
p
[0]
. If
p
[0] >
h
[
i
]
, then
h
[
i
]
goes to the right
t
seconds and reads all tracks on its way. Otherwise if
p
[0] ≤
h
[
i
]
, then the head has two choices:
- go to the right
seconds, then
to the left and h[i] - p[0] again to the left;
- go to the left h[i] - p[0] seconds, then h[i] - p[0] to the right and t - 2·(h[i] - p[0]) again to the right.
Obviously, for h[i] it is more advantageous to visit the track positioned as much as possible to the right. So we choose by . Then we move the pointer onto the first unread track, and repeat the algorithm for h[i + 1], and so on with each head.
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cmath>
using namespace std;
#define LL long long
LL h[100005],p[100005];
int n,m;
bool fuck(LL t){
int cur=1;LL go;
for(int i=1;i<=n;i++){ //这里从第一个要读的轨道开始,看哪一个探头可以读了它
if(abs(p[cur]-h[i])>t)continue;
if(p[cur]==h[i]) cur++; //如果一开始就有一个在它上面,直接往后找
if(p[cur]<h[i]) go=max(h[i]+t-2*(h[i]-p[cur]),h[i]+(t-(h[i]-p[cur]))/2);//因为是从小到大排列的轨道,这个看思路
else go=h[i]+t; //如果该轨道是在探头的右边,直接把这个探头往右移,这是最节省时间的
while(go>=p[cur]&&cur<=m) cur++; //把这个探头往右移的路上的轨道一并读了。
}
return cur>m; //把所有的探头用完或者没用完之后看是不是能读完m个
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++)
cin>>h[i];
for(int i=1;i<=m;i++)
cin>>p[i];
LL l=0,r=abs(p[1]-h[1])*2+abs(p[m]-h[1]);
LL mid;
while(l<=r){
mid=(l+r)>>1;
if(fuck(mid)) r=mid-1; //如果能读完,说明时间是比最小时间大的,往左边找这个t
else l=mid+1; //不能读完,也就是说时间不够,往右边找这个t
}
cout<<l<<endl;
return 0;
}