2019 沈阳网络赛 F.Honk's pool(二分)

每次挑出最大的,令其减一,然后挑出最小的,令其加一。共操作K 次,求最大值和最小值的差。

可以显然预见到如果操作次数无限,那么所有池子的水量就会在平均值附近徘徊。

但是k不是无限的,有可能到不了平均,因此可以讲平均值作为上下界,对最大最小值分别进行二分。

#include 

using namespace std;
typedef long long ll;
const int maxn = 5e5 + 5;

int n, k, a[maxn], low, high;
ll avg;

bool check(int x, bool f) {
    ll sum = 0;
    for (int i = 0; i < n; ++i) {
        if (a[i] > x && f) {
            sum += a[i] - x;
        } else if (a[i] < x && !f) {
            sum += x - a[i];
        }
    }
    return sum <= k;
}

void solve() {
    int l = *min_element(a, a + n), r = high, mid, minn, maxx;
    while (l <= r) {
        mid = (l + r) >> 1;
        if (check(mid, 0)) {
            minn = mid;
            l = mid + 1;
        } else {
            r = mid - 1;
        }
    }
    l = low, r = *max_element(a, a + n);
    while (l <= r) {
        mid = (l + r) >> 1;
        if (check(mid, 1)) {
            maxx = mid;
            r = mid - 1;
        } else {
            l = mid + 1;
        }
    }
    printf("%d\n", maxx - minn);
}

int main() {
    while (~scanf("%d%d", &n, &k)) {
        avg = 0;
        for (int i = 0; i < n; ++i) {
            scanf("%d", &a[i]);
            avg += a[i];
        }
        low = avg / n + (avg % n != 0);
        high = avg / n;
        solve();
    }
    return 0;
}

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