Codeforces 200 div1 C. Read Time

題目:Codeforces 200 div1 C. Read Time

 tag :二分

思路:開始思路二分沒錯,就是忽略了一種情況。

貪心想的話是,對於當前能訪問到的地方儘量先訪問,從左往右。但是有可能會忽略的是,先往右邊掃,然後再往左,也有可能是先往左掃,再往右掃。

細節注意點,不然會Wa的很慘。


#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;
#define maxn 100010
int m,n;
long long h[maxn],p[maxn];
const long long inf = 200000000010LL;
bool ok(long long mid)
{
    int cnt,tmp=1;
    for(cnt=1;cnt<=n;cnt++)
    {
        // case 1 , 往左讀兩遍,往右一遍
        // case 2 , 往右讀兩遍,往左一遍
        if(h[cnt]+mid<p[tmp])
            continue;
        if(h[cnt]-mid>p[tmp])
            return false;
        long long pp=max(p[tmp]+mid-abs(h[cnt]-p[tmp]),h[cnt]+(mid-abs(h[cnt]-p[tmp]))/2);
        while(p[tmp]<=pp && tmp<=m)
            tmp++;
        if(tmp==m+1)
        return true;
    }
    return false;
}
int main()
{
    while(cin>>n>>m)
    {
        for(int i=1;i<=n;i++)
            cin>>h[i];
        for(int i=1;i<=m;i++)
            cin>>p[i];
        long long l=0,r=inf,mid,ans;
        int cas=1000;
        while(l<r && cas--)
        {
            mid=(l+r)/2;
            //cout<<l<<":"<<r<<":"<<mid<<":"<<ans<<endl;
            if(ok(mid))
            {
                ans=mid;
                r=mid;
            }
            else
                l=mid+1;
        }
        cout<<ans<<endl;
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章