uva-10954-貪心
阿新 • • 發佈:2018-11-10
題意:倆個數相加,產生的和就是這次加法的代價,問,所有數都加起來,最小代價是多少
解題思路:貪心,每次都選取最小倆個數相加,如果只有一個數,計算完畢,注意,加法的和要再次入佇列。
#include <string> #include<iostream> #include<map> #include<memory.h> #include<vector> #include<algorithm> #include<queue> #include<vector> namespacecc { using std::cout; using std::endl; using std::cin; using std::map; using std::vector; using std::string; using std::sort; using std::priority_queue; using std::greater; using std::vector; constexpr int N = 5000; priority_queue<int,vector<int>, greater<int> >q; void read(int n) { while (q.empty() == false) q.pop(); int k = 0; while (n--) { cin >> k; q.push(k); } } void solve() { int n;while (cin >> n && n) { read(n); int cost = 0; while (q.empty() == false) { int sum = 0; int i = q.top(); q.pop(); if (q.empty() == true) break; int k = q.top(); q.pop(); sum = i + k; cost =cost+sum; q.push(sum); } cout << cost << endl; } } }; int main() { #ifndef ONLINE_JUDGE freopen("d://1.text", "r", stdin); #endif // !ONLINE_JUDGE cc::solve(); return 0; }