洛谷 P1873 砍树 二分

题目
二分答案,在满足木材长度大于等于N的情况下,锯片尽可能的高。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <iomanip>
#include <queue>
#include <map>
#include <cstring>
#include <algorithm>
using namespace std;

typedef long long ll;

int N, M, max_len = -1;
int wood[1000000];
int Find(int L, int R) 
{
    int max_high = -1;
    while (L <= R) {
        int mid = L + (R - L) / 2;
        ll sum = 0;//sum为所得木材的总长度
        for (int i = 0; i < N; i++) {
            if (wood[i] > mid) {
                sum += wood[i] - mid;
            }
        }
        if (sum >= M) {//如果木材长度大于等于M,继续向右找,保存最大的高度
            max_high = max(max_high, mid);
            L = mid + 1;
        }
        else {
            R = mid - 1;
        }
    }
    return max_high;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> N >> M;
    for (int i = 0; i < N; i++) {
        cin >> wood[i];
        max_len = max(max_len, wood[i]);
    }
    int ans = Find(0, max_len);
    cout << ans << endl;
    return 0;
}

发布了36 篇原创文章 · 获赞 0 · 访问量 2061

猜你喜欢

转载自blog.csdn.net/weixin_43971049/article/details/104193895
今日推荐