【二分】【边界判定】

https://ac.nowcoder.com/acm/contest/22353/G
注意点:check中,不仅要判断用的joker数是否大于joker牌的数量,还要判断组成套数是否小于用的joker数量,

原文链接:https://blog.csdn.net/a_forever_dream/article/details/106548941

#include<bits/stdc++.h>

typedef long long ll;
using namespace std;

bool check(ll goal, ll* a, int n, int m) {
    ll joker_count = 0;
    for(int i = 0; i < n; i++) {
        if(a[i] < goal) {
            joker_count += goal - a[i];
        }
    }
    return joker_count <= m && joker_count <= goal; // 只需要判断 joker 数量是否超过了 m
}

int main() {
    int n, m;
    cin >> n >> m;
    ll a[50];
    ll total_cards = 0;  // 记录所有牌的总数
    
    // 读取每种牌的数量并计算总牌数
    for(int i = 0; i < n; i++) {
        cin >> a[i];
        total_cards += a[i];
    }
    
    ll low = 1; // low 最小从 1 开始
    ll high = total_cards + m; // high 设置为总牌数加上 Joker 数量
    
    ll ans = 0;
    while(low <= high) {
        ll mid = (low + high) / 2; // 中间值
        if(check(mid, a, n, m)) {
            ans = mid;  // 更新答案为 mid,因为 mid 满足条件
            low = mid + 1; // 继续尝试更大的值
        } else {
            high = mid - 1; // 尝试更小的值
        }
    }
    
    cout << ans << endl;
    return 0;
}

posted @ 2024-10-05 14:47  peterzh6  阅读(2)  评论(0编辑  收藏  举报