문제 : https://www.acmicpc.net/problem/1715


[알고리즘풀이]

현재 카드 N 묶음 중 가장 작은 2개를 합치고, 다시 N - 1 묶음 중 가장 작은 2개를 합치는 방식으로 진행했을 때, 최솟값이 나옴을 알 수 있다. 매번 sort를 진행해 가장 작은 2개를 찾게 된다면, 시간 초과를 마주할 것이다.

따라서, 우선순위 큐를 활용해서 문제를 해결해야 한다.

#include<iostream>
#include<queue>

using namespace std;

long long sum = 0;
priority_queue<int, vector<int>, greater<int>> q;

int main(void) {
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		int temp;
		cin >> temp;
		q.push(temp);
	}
	while (q.size() != 1) {
		int temp;
		temp = q.top();
		q.pop();
		temp += q.top();
		q.pop();
		sum += temp;
		q.push(temp);
	}
	cout << sum;
}

 

'Problem Solving > BOJ' 카테고리의 다른 글

[BOJ] 9421 - Happy Prime Number  (0) 2019.10.03
[BOJ] 1456 - 거의 소수  (0) 2019.10.03
[BOJ] 2225 - 합분해  (0) 2019.10.01
[BOJ] 1914 - 하노이 탑  (0) 2019.10.01
[BOJ] 2003 - 수들의 합  (0) 2019.09.30

+ Recent posts