UVALive 6533

哈夫曼树  倒过来思考 ~ 

最深的叶子 值为1  所以最深的先出队列 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

struct node
{
    long long d, v;
    node(int i, int j)
    {
        d = i, v = j;
    }
    node() {}
    bool operator < (node a) const
    {
        return d < a.d || (d == a.d && v > a.v);
    }
};

priority_queue <node> q;

int main()
{
    int n;
    while (scanf("%d", &n) != EOF)
    {
        for (int i = 0; i < n; i++)
        {
            int x;
            scanf("%d", &x);
            q.push(node(x, 0));
        }
        long long a, b, ans = 0, val = 1;
        while((int)q.size() >= 2)
        {
            int cur = q.top().d;
            a = q.top().v, q.pop();
            b = q.top().v, q.pop();
            if (!a)
                a = val;
            if (!b)
                b = val;
            val = max(val, max(a, b));
            node t;
            t.d = cur - 1, t.v = a + b;
            q.push(t);
        }
        ans = q.top().v, q.pop();
        printf("%lld\n", ans);
    }
    return 0;
}


posted @ 2014-05-03 16:06  xlc2845  阅读(128)  评论(0编辑  收藏  举报