Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 백트래킹
- mst
- Network
- 후니의 쉽게 쓴 시스코 네트워킹
- 그리디
- 수학
- BFS
- java
- 에라토스테네스의 체
- 투 포인터
- 스택
- swea
- dfs
- 백준
- 위상정렬
- 시뮬레이션
- 유니온 파인드
- 동적계획법
- 세그먼트 트리
- 이분탐색
- 알고리즘
- 구현
- 프로그래머스
- Effective Java
- JUnit 5
- 완전탐색
- CS
- 플로이드-와샬
- 문자열
- Kotlin
Archives
반갑습니다!
[백준] 1715 카드 정렬하기 본문
풀이
가장 작은 숫자의 카드끼리 섞어야한다는 것은 직관적으로 알 수 있다. 따라서 우선순위 큐를 사용해서 구현했다.
코드
C++
#include <iostream>
#include <queue>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
priority_queue<int, vector<int>, greater<int>> pq;
for (int i = 0; i < n; i++) {
int tmp;
cin >> tmp;
pq.push(tmp);
}
int ans = 0;
while (pq.size() > 1) {
int n1 = pq.top();
pq.pop();
int n2 = pq.top();
pq.pop();
int sum = n1 + n2;
ans += sum;
pq.push(sum);
}
cout << ans << '\n';
return 0;
}
Python3
import sys
import heapq
n = int(sys.stdin.readline().strip())
card = []
for i in range(n):
heapq.heappush(card, int(sys.stdin.readline().rstrip()))
answer = 0
while len(card) > 1:
a = heapq.heappop(card)
b = heapq.heappop(card)
answer += (a + b)
heapq.heappush(card, a + b)
print(answer)
'알고리즘 문제 풀이' 카테고리의 다른 글
[백준] 1939 중량제한 (0) | 2020.09.24 |
---|---|
[백준] 1822 차집합 (0) | 2020.09.23 |
[백준] 2012 등수매기기 (0) | 2020.09.23 |
[프로그래머스] 두 개 뽑아서 더하기 (0) | 2020.09.22 |
[프로그래머스] 삼각 달팽이 (0) | 2020.09.22 |