標籤: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