forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
44 lines (34 loc) · 918 Bytes
/
main.cpp
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
32
33
34
35
36
37
38
39
40
41
42
43
44
/// Source : https://leetcode.com/problems/minimum-cost-to-connect-sticks/
/// Author : liuyubobobo
/// Time : 2019-08-24
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/// Greedy
/// Time Complexity: O(nlogn)
/// Space Complexity: O(n)
class Solution {
public:
int connectSticks(vector<int>& sticks) {
priority_queue<int, vector<int>, greater<int>> pq;
for(int stick: sticks) pq.push(stick);
int res = 0;
while(pq.size() > 1){
int cost = pq.top();
pq.pop();
cost += pq.top();
pq.pop();
res += cost;
pq.push(cost);
}
return res;
}
};
int main() {
vector<int> sticks1 = {2, 4, 3};
cout << Solution().connectSticks(sticks1) << endl;
vector<int> sticks2 = {1, 8, 3, 5};
cout << Solution().connectSticks(sticks2) << endl;
return 0;
}