학부 수업 정리/알고리즘연습 (22-1)
[알고연] (3주차-3) 160A. Twins
퐁키조아
2022. 3. 25. 14:49
160A. Twins
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.
As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.
이 문제도 그리디로 접근하면 매우 쉽다. 먼저 돈들을 입력받고 내림차순으로 정렬한 뒤, 가장 큰 돈부터 가져간다. 돈을 가져갈 때마다 total 금액에 더해주고 remain 금액은 빼준다. 그러다가 돈이 하나도 안 남았거나 total이 remain보다 커질 경우 그만두면 된다.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n; cin >> n;
vector<int> vec(n);
int total = 0, remain = 0, cnt = 0;
for (int i = 0; i < n; i++) { cin >> vec[i]; remain += vec[i]; }
sort(vec.begin(), vec.end(), greater<>());
while (true) {
if (total > remain || vec.size() == 0) break;
total += vec[0]; remain -= vec[0];
vec.erase(vec.begin());
cnt++;
}
cout << cnt << "\n";
return 0;
}