【二分】【邊界判定】

peterzh6發表於2024-10-05

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;
}

相關文章