AcWing 102. 最佳牛围栏(二分)

传送门

#include 

using namespace std;

const int maxn = 1e5 + 10;
int n, f, cows[maxn];
double sum[maxn];

bool Check(double mid) {
    for (int i = 1; i <= n; i++)
        sum[i] = sum[i - 1] + cows[i] - mid;
    double minV = 0;
    for (int i = 0, j = f; j <= n; i++, j++) {
        minV = min(minV, sum[i]);
        if (sum[j] > minV)
            return true;
    }
    return false;
}

int main() {
    //freopen("in", "r", stdin);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> n >> f;
    for (int i = 1; i <= n; i++)
        cin >> cows[i];
    double l = 0, r = 2000;
    while (r - l > 1e-5) {
        double mid = (l + r) / 2;
        if(Check(mid))
            l = mid;
        else
            r = mid;
    }
    cout << int(r * 1000) << endl;
    return 0;
}

你可能感兴趣的:(其它,进阶指南)