https://www.acmicpc.net/problem/7450
7450번: Bin Packing
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs. The fir
www.acmicpc.net
코드:
#include <iostream>
#include <algorithm>
using namespace std;
int item[111111];
int n, bin;
int main(void) {
cin >> n;
cin >> bin;
for (int i = 0; i < n; i++) cin >> item[i];
sort(item, item + n);
int l = 0, r = n - 1, cnt = 0;
while (l <= r) {
if (item[l] + item[r] <= bin) l++;
r--;
++cnt;
}
cout << cnt;
return 0;
}
|
cs |
그리디 증명:
Bin에는 2개까지 들어가므로 가능하다면 1개보다 2개를 담는 것이 낫습니다.
그리고 Bin에 담기지 않은 item은 최대 값과 최소 값을 합쳐야, 최대 값을 제거할 때 item[l] + item[r] <= bin일 확률이 가장 높으므로 그리디가 성립합니다.
풀이:
정렬 후 투 포인터 알고리즘을 이용합니다.
'백준(C, C++) > 골드' 카테고리의 다른 글
백준 3078: 좋은 친구 [C/C++] (0) | 2022.06.11 |
---|---|
백준 15961: 회전 초밥 [C/C++] (0) | 2022.06.07 |
백준 2357 최솟값과 최댓값 c++ (0) | 2022.06.02 |
백준 11505 구간 곱 구하기 (0) | 2022.06.02 |
백준 15685 드래곤 커브 - [C/C++] 삼성 코딩테스트 (0) | 2022.05.29 |