UVA 1335 Beijing Guards 二分贪心

--------

const int maxn=110000;
const int maxm=10000;
int n;
int a[maxn];
int lb[maxn],rb[maxn];
bool C(int x){
    lb[0]=a[0];
    rb[0]=0;
    for (int i=1;i<n;i++){
        if (i&1){
            if (lb[i-1]+a[i]<=a[0]){
                lb[i]=a[i];
                rb[i]=0;
            }
            else{
                lb[i]=a[0]-lb[i-1];
                rb[i]=a[i]-lb[i];
            }
        }
        else{
            if (rb[i-1]+a[i]<=x-a[0]){
                rb[i]=a[i];
                lb[i]=0;
            }
            else{
                rb[i]=x-a[0]-rb[i-1];
                lb[i]=a[i]-rb[i];
            }
        }
        if (lb[i]+lb[i-1]>a[0]||rb[i]+rb[i-1]>x-a[0]) return false;
        if (lb[i]+rb[i]>x) return false;
        if (lb[i]<0||rb[i]<0) return false;
    }
    if (lb[n-1]) return false;
    return true;
}
int main(){
    int l,r,ans;
    while (~scanf("%d",&n)){
        if (n==0) break;
        for (int i=0;i<n;i++) scanf("%d",&a[i]);
        if (n==1){
            printf("%d\n",a[0]);
            continue;
        }
        l=r=ans=0;
        for (int i=0;i<n;i++) l=max(l,a[i]+a[(i+1)%n]);
        if (n%2==0){
            printf("%d\n",l);
            continue;
        }
        r=100000;
        while (l<=r){
            int mid=(l+r)>>1;
            if (C(mid)){
                ans=mid;
                r=mid-1;
            }
            else l=mid+1;
        }
        printf("%d\n",ans);
    }
	return 0;
}


--------

你可能感兴趣的:(UVA 1335 Beijing Guards 二分贪心)