[BOJ] 2512λ² | μμ° (C++)
2023. 9. 6. 22:00γCoding Test/BOJ
πλ¬Έμ 보λ¬κ°κΈ°
π§π»νμ΄ κ³Όμ
맀κ°λ³μ νμμΌλ‘ ν μ μμ΅λλ€. μ λ λ€μκ³Ό κ°μ΄ νμμ΅λλ€.
- μ λ ₯ λ°μ μμ°λ€μ μ€λ¦μ°¨μμΌλ‘ μ λ ¬ν©λλ€.
- μμ°λ€μ ν©κ³κ° M μ΄νλΌλ©΄, μμ°λ€ μ€ μ΅λκ°(λ°°μ΄μ λ§μ§λ§ κ°)μ μΆλ ₯νκ³ μ’ λ£ν©λλ€.
- κ·Έκ² μλλΌλ©΄, μ΅μ μμ°κ°(1)κ³Ό μ΅λ μμ°κ°(λ°°μ΄μ λ§μ§λ§ κ°)μ κ°μ§κ³ μ΄λΆ νμμ μμν©λλ€.
- "mid = (left + right) / 2" κ°μ κ³μ°ν©λλ€.
- μμ°μ μ΄ ν©κ³λ₯Ό κ³μ°νλ, mid κ°λ³΄λ€ ν° μμ°μ mid κ°μΌλ‘ ν©κ³μ λν©λλ€.
- λ€ λν μ΄ ν©κ³κ° M μ΄νλΌλ©΄, left = mid + 1μ νκ³ max(mid, μ΄μ mid)λ‘ κ°±μ ν©λλ€.
- μλλΌλ©΄, right = mid - 1μ μ μ©ν©λλ€.
- left > rightκ° λ λκΉμ§ μ κ³Όμ μ λ°λ³΅ν©λλ€.
βοΈμμ€ μ½λ λ° κ²°κ³Ό
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#define FAST_IO cout.tie(NULL); cin.tie(NULL); ios::sync_with_stdio(false);
using namespace std;
using uint32 = unsigned int;
int main()
{
FAST_IO
int N;
cin >> N;
vector<uint32> budgets(N);
for (int i = 0; i < N; i++)
cin >> budgets[i];
sort(budgets.begin(), budgets.end());
uint32 start = 1, last = budgets.back();
uint32 M;
cin >> M;
if (accumulate(budgets.begin(), budgets.end(), 0) <= M)
{
cout << budgets.back();
return 0;
}
uint32 answer = 0;
while (start <= last)
{
uint32 mid = (start + last) / 2;
uint32 money = 0;
for (const auto& budget : budgets)
money += (budget <= mid) ? budget : mid;
if (money <= M)
{
start = mid + 1;
answer = max(answer, mid);
}
else
last = mid - 1;
}
cout << answer;
return 0;
}
728x90
λ°μν
'Coding Test > BOJ' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[BOJ] 9935λ² | λ¬Έμμ΄ νλ° (C++) (1) | 2023.10.08 |
---|---|
[BOJ] 2110λ² | 곡μ κΈ° μ€μΉ (C++) (0) | 2023.10.08 |
[BOJ] 1300λ² | Kλ²μ§Έ μ (C++) (0) | 2023.09.06 |
[BOJ] 13335λ² | νΈλ (C++) (0) | 2023.09.04 |
[BOJ] 1654λ² | λμ μλ₯΄κΈ° (C++) (0) | 2023.09.02 |