UVALive 6656 Watching the Kangaroo --二分

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   ar   

題意:給你一些區間,再查詢一些點,問這些點與所有區間形成的最小距離的最大值。最小距離定義為:如果點在區間內,那麼最小距離為0,否則為min(pos-L[i],R[i]-pos)。

解法:當然要排個序,仔細想想會發現我們要找的區間的位置滿足二分性質,即如果此時pos-L[mid] >= R[mid]-pos,那麼我們要找的區間肯定是mid或大於mid,否則,我們要找的區間一定是mid即mid以下。二分找到即可。預先處理時要把嵌套在別的區間裡的區間忽略掉,因為外面那個區間一定比他更優。

代碼:

#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <cmath>#include <algorithm>#define ll long longusing namespace std;#define N 100007#define M 22struct node{    ll l,r;}p[N],np[N];ll L[N],R[N];int tot;ll pos;int cmp(node ka,node kb){    return ka.l < kb.l;}ll get(int mid){    if(mid > tot || mid < 1)        return 0;    if(L[mid] > pos || R[mid] < pos)        return 0;    return min(pos-L[mid],R[mid]-pos);}int main(){    int t,cs = 1,n,m,i,j;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&m);        for(i=1;i<=n;i++)            scanf("%lld%lld",&p[i].l,&p[i].r);        sort(p+1,p+n+1,cmp);        tot = 1;        for(i=2;i<=n;i++)        {            if(p[i].r > p[tot].r)            {                tot++;                p[tot] = p[i];            }        }        for(i=1;i<=tot;i++)        {            L[i] = p[i].l;            R[i] = p[i].r;        }        printf("Case %d:\n",cs++);        while(m--)        {            int ans = 0;            scanf("%lld",&pos);            int low,high;            low = 1,high = tot;            while(low <= high)            {                int mid = (low+high)/2;                if(R[mid]-pos <= pos-L[mid])                    low = mid+1;                else                    high = mid-1;            }            printf("%lld\n",max(get(low),get(high)));        }    }    return 0;}
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.