์‹ค๋ฒ„3 : ์ด์ง„ ํƒ์ƒ‰ ๋ฌธ์ œ์ด๋‹ค.

ํ’€์ด

์˜ˆ์‚ฐ ๊ธˆ์•ก์€ ์ตœ๋Œ€์˜ˆ์‚ฐ๊ณผ ์•„์˜ˆ ์•ˆ์ฃผ๋Š”(0์›) ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค. ๋”ฐ๋ผ์„œ 0๊ณผ max๊ธˆ์•ก์„ ์–‘ ๋์œผ๋กœ ์žก๋Š”๋‹ค.

:-::-::-::-::-:
leftrightmid์˜ˆ์‚ฐ์†Œ๋ชจ๊ธˆ์•กํ›„๋ณด๊ฐ€๋Šฅ์—ฌ๋ถ€
015075300O
75150112446O
113150131492X
113130121472O
122130126482O
126129127484O
128129128486X

mid๊ฐ€ m๋ณด๋‹ค ์ž‘์œผ๋ฉด ๋‹ต์˜ ํ›„๋ณด๋ผ๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค. ํƒ์ƒ‰์€ ํ•˜๋˜, ๋‹ต์ธ ์ƒํ™ฉ๋งŒ ์ž˜ ๊ฐ€์ ธ์˜ค๋ฉด ๋จ.

Code

//
//  main.cpp
//  algorithm_prac
//
//  Created by ์ตœ์™„์‹ on 2021/04/05.
//
 
#include <iostream>
#include <algorithm>
typedef long long ll;
using namespace std;
int req[10001];
 
 
 
bool comp(int a, int b){
    return a<b;
}
 
int main(){
    int n, total = 0;
    ll m = 0;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> req[i];
        total += req[i];
    }
    cin >> m;
    
    sort(req, req+n, comp);
    
    if (total < m) {
        cout << req[n-1] << '\n';
        return 0;
    }
    
    int left = 0, right = req[n-1];
    int ans = 0;
    while (left <= right) {
        int mid = (left+right)/2;
        ll sum = 0;
        for (int i = 0; i < n; i++) {
            if (mid < req[i]) sum += mid;
            else sum += req[i];
        }
        if (sum > m) {
            right = mid-1;
        } else {
            ans = mid;
            left = mid+1;
        }
    }
    
    cout << ans << '\n';
    return 0;
}
 

Reference