uva 10954 Add All

题意:每次选出最小的两个数相加,这些数包括过程中得出的结果,直到都用过了,相当育Huffman算法的实现,用到了优先队列
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
#include <cstdlib>
using namespace std;
const int MAXN = 5005;

int n;
int a[MAXN],sum[MAXN];

struct cmp
{
    bool operator()(const int a,const int b) 
    {
        return a > b;   // 数字大的优先级反而比较小
    }
};

priority_queue<int, vector<int>, cmp> q;

void init()
{
    memset(sum,0,sizeof(sum));
    while (!q.empty())
        q.pop();
}

int main()
{
    while (scanf("%d",&n) != EOF && n)
    {
        init();
        int ans = 0,tot = 0;
        for (int i = 0; i < n; i++)
        {
            int a;
            scanf("%d",&a);
            q.push(a);
        }
        if (q.size() == 1)
            ans = q.top();
        while (q.size() != 1)
        {
            int num = 0;
            num += q.top();
            q.pop();
            num += q.top();
            q.pop();
            sum[tot++] = num;
            q.push(num);
        }
        for (int i = 0; i < n-1; i++)
            ans += sum[i];
        printf("%d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(uva 10954 Add All)