# 洛谷P3124 [USACO15OPEN]被困在haybales（银）Trapped in the H…

http://www.cnblogs.com/CQzhangyu/p/6430440.html

 1 #include <bits/stdc++.h>
2 #define For(i,j,k) for(int i=j;i<=k;i++)
3 #define Dow(i,j,k) for(int i=j;i>=k;i--)
4 #define LL long long
5 using namespace std ;
6
7 const int N = 100011,inf=1e9 ;
8 struct node{
9     int h,pos ;
10 }point[N] ;
11 int n,m,Mn,w,id,l,r ;
12 int f[N] ;
13
15     int x = 0 , f = 1 ;
16     char ch = getchar() ;
17     while(ch<'0'||ch>'9') { if(ch=='-') f = -1 ; ch = getchar() ; }
18     while(ch>='0'&&ch<='9') { x = x * 10+ch-48 ; ch = getchar() ; }
19     return x * f ;
20 }
21
22 inline bool cmp(node a,node b) {
23     return a.pos < b.pos ;
24
25 }
26
27 int main()
28 {
31     point[++n].pos = m ;
32     sort(point+1,point+n+1,cmp) ;
33     For(i,1,n)
34         if(point[i].pos==m) {
35             m = i ;
36             break ;
37         }
38     f[m] = -inf ;
39     Dow(i,m-1,1) f[i] = max(f[i+1], point[i].h+point[i].pos ) ; //左边增加，右边不变
40     For(i,m+1,n) f[i] = max(f[i-1], point[i].h-point[i].pos ) ;
41
42
43     Mn = inf ;
44     For(i,m+1,n) {
45         l = 1 ; r = m ;
46         while(l<r) {
47             int mid = (l+r)/2 ;
48             if( point[i].pos-point[mid].pos<=point[i].h )   //   右边不用增加
49                 r = mid ;
50             else
51                 l = mid+1 ;
52         }
53         if(r<m) Mn = min(Mn,max(0,point[i].pos-f[r]) ) ;
54     }
55
56     For(i,1,m) {
57         l = m ; r = n ;
58         while(l<r) {
59             int mid = (l+r+1)/2 ;    //
60             if( point[mid].pos-point[i].pos<=point[i].h )   //   左边不用增加
61                 l = mid ;   //
62             else
63                 r = mid-1 ;  //
64         }
65         if(l>m) Mn = min(Mn,max(0,-f[l]-point[i].pos)  ) ;   //  //
66     }
67     if(Mn==inf) printf("-1\n") ;
68     else printf("%d\n",Mn) ;
69     return 0 ;
70 }

posted @ 2017-10-14 10:05  third2333  阅读(351)  评论(0编辑  收藏  举报