uva1450-Airport

二分上限。如果只有一边有飞机就直接起飞。否则,将起飞机会保留下来,根据后面的情况做决定。值得注意的是suml + sumr >= chance。

const int maxn = 5010;
int a[maxn], b[maxn];
int n;

bool judge(int limit) {
    int l = 0, r = 0, cnt = 0;
    for (int i = 0;i < n;++i) {
        l += a[i];
        r += b[i];

        int ll = max(l - limit, 0);
        int rr = max(r - limit, 0);

        if (ll + rr > cnt) return false;

        if (l == 0 && r > 0)
            r--;
        else if (r == 0 && l > 0)
            l--;
        else if (l > 0 && r > 0 && l + r > cnt)
            //Because chances must <= the number of aircrift
            cnt++;
    }
    return true;
}

int solve(int l,int r) {
    while(l < r) {
        int mid = (l + r) >> 1;
        if (judge(mid)) r = mid;
        else l = mid + 1;
    }
    return max(r - 1, 0);
}

int main(int argc, const char * argv[])
{   
    // freopen("in.txt","r",stdin);
    // freopen("out.txt","w",stdout);
    // clock_t _ = clock();

    int t;
    cin >> t;
    while(t--) {
        scanf("%d", &n);
        int l = 0, r = 0;
        for (int i = 0;i < n;++i) {
            scanf("%d %d", &a[i], &b[i]);
            l += a[i];
            r += b[i];
        }

        printf("%d\n", solve(0, max(l, r)));
    }

    // printf("\nTime cost: %.2fs\n", 1.0 * (clock() - _) / CLOCKS_PER_SEC);
    return 0;
}

你可能感兴趣的:(二分)