UVA 10954 Add All (全部相加)(Huffman编码 + 优先队列)

题意:有n(n <= 5000)个数的集合S,每次可以从S中删除两个数,然后把它们的和放回集合,直到剩下一个数。每次操作的开销等于删除的两个数之和,求最小总开销。所有数均小于10^5。

分析:按此操作,最终变成1个数,需要n-1次操作,要想总开销最小,就使每次取出的两数之和最小,优先队列。

#pragma comment(linker, "/STACK:102400000, 102400000")
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define Min(a, b) ((a < b) ? a : b)
#define Max(a, b) ((a < b) ? b : a)
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const double eps = 1e-8;
const int MAXN = 500 + 10;
const int MAXT = 10000 + 10;
using namespace std;
priority_queue<int, vector<int>, greater<int> > q;
int main(){
    int n;
    while(scanf("%d", &n) == 1){
        if(!n) return 0;
        while(!q.empty()) q.pop();
        for(int i = 0; i < n; ++i){
            int x;
            scanf("%d", &x);
            q.push(x);
        }
        int ans = 0;
        while(q.size() > 1){
            int a = q.top(); q.pop();
            int b = q.top(); q.pop();
            ans += a + b;
            q.push(a + b);
        }
        printf("%d\n", ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/6371404.html