這題不是單純由小加到大,考慮 4 5 5 6 7 這數列,4+5+5=14之後,應該要做6+7=13,之後再做13+14=27。
因此每次都選擇兩個最小的數字相加,然後變成一個數字,然後丟回數列裡面,重複至數列只剩一個數字。
借這題順便練習一下priority_queue,它有三個參數priority_queue<type, container, function>,container有兩種,可以用vector<>和deque<>,function也有兩個,less<>將最大的元素放在top,greater<>將最小的元素放在top。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <queue> | |
using namespace std; | |
int main() | |
{ | |
int N, x; | |
while (scanf("%d", &N) && N) { | |
priority_queue<int, vector<int>, greater<int>> PQ; | |
for (int i = 0; i < N; ++i) { | |
scanf("%d", &x); | |
PQ.push(x); | |
} | |
int cost = 0; | |
while (PQ.size() != 1) { | |
x = PQ.top(); PQ.pop(); | |
x += PQ.top(); PQ.pop(); | |
cost += x; | |
PQ.push(x); | |
} | |
printf("%d\n", cost); | |
} | |
return 0; | |
} |
沒有留言:
張貼留言