哈夫曼树

  给定n个权值作为n个叶子结点,构造一棵二叉树,若带权路径长度达到最小,称这样的二叉树为最优二叉树,也称为哈夫曼树(Huffman tree)。结点的带权路径长度为:从根结点到该结点之间的路径长度与该结点的权的乘积。树的带权路径长度规定为所有叶子结点的带权路径长度之和。

哈夫曼树_第1张图片

  1*3+2*3+3*2+4*1  = (1+2)+(1+2+3)+(1+2+3+4) =19

  整个树的带权路径也等于除叶节点以外其它节点的权的和(父节点的权值等于它子节点的和)。构造哈夫曼树的时候每次取出2个权值最小的元素加到树里,然后把这两个元素从集合中删除,把它们的和(父节点)作为一个新元素加到集合中。重复这个操作,直到剩最后一个元素在集合中,再把最后一个元素加到树里。为什么这样做呢?其实这是一种贪心的思想,比如把上图的2和3换位置,最下面那个父节点权值变大,中间的父节点权值不变,总的还是变大了。离根越远的加的次数越多,所以尽量把小的数放的远。。


C - Fence Repair
Time Limit:2000MS    Memory Limit:65536KB    64bit IO Format:%I64d & %I64u
Submit Status Practice POJ 3253

Description

Farmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needsN (1 ≤ N ≤ 20,000) planks of wood, each having some integer lengthLi (1 ≤ Li ≤ 50,000) units. He then purchases a single long board just long enough to saw into theN planks (i.e., whose length is the sum of the lengths Li). FJ is ignoring the "kerf", the extra length lost to sawdust when a sawcut is made; you should ignore it, too.

FJ sadly realizes that he doesn't own a saw with which to cut the wood, so he mosies over to Farmer Don's Farm with this long board and politely asks if he may borrow a saw.

Farmer Don, a closet capitalist, doesn't lend FJ a saw but instead offers to charge Farmer John for each of theN-1 cuts in the plank. The charge to cut a piece of wood is exactly equal to its length. Cutting a plank of length 21 costs 21 cents.

Farmer Don then lets Farmer John decide the order and locations to cut the plank. Help Farmer John determine the minimum amount of money he can spend to create theN planks. FJ knows that he can cut the board in various different orders which will result in different charges since the resulting intermediate planks are of different lengths.

Input

Line 1: One integer N, the number of planks
Lines 2.. N+1: Each line contains a single integer describing the length of a needed plank

Output

Line 1: One integer: the minimum amount of money he must spend to make N-1 cuts

Sample Input

3
8
5
8

Sample Output

34

Hint

He wants to cut a board of length 21 into pieces of lengths 8, 5, and 8.
The original board measures 8+5+8=21. The first cut will cost 21, and should be used to cut the board into pieces measuring 13 and 8. The second cut will cost 13, and should be used to cut the 13 into 8 and 5. This would cost 21+13=34. If the 21 was cut into 16 and 5 instead, the second cut would cost 16 for a total of 37 (which is more than 34).

 

这个题其实就是个哈夫曼树,切多长的木头就要花多少钱,问花的最少的钱是多少。。可以反过来想,把木头拼起来,每次先拼短的好(假设有1,2,100和一些别的长度,肯定是先拼1,2,再把1,2跟别的拼上,最后拼100比先拼1,100再拼别的最后拼2好),或者可以画个哈夫曼树的图看得更清楚,除了叶子节点外的节点都是要花的钱。这道题数据量大,每次都快排取最小值会超时(每次操作大多数元素已经有序,快排浪费了很多不必要的比较时间),于是用最小堆来做,堆的每次操作复杂度都是O(lgn)。

第一次正儿八经自己写的堆。。写了添加元素,维护堆,建堆,返回并删除最小元素的函数。。一开始可以把a输完了再调用建堆函数,也可以输一个添加一个。注意操作要进行N-1次。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<map>
#include<queue>
#include<stack>
using namespace std;
long long a[20010], l;
void heap_add(int n)  //n 值
{
    int child=l+1,fa=child/2;
    while(fa>0&&a[fa]>n)
    {
        a[child]=a[fa];
        child=fa;
        fa=fa/2;
    }
    a[child]=n;
    l++;
}

void heap_adjust(int x)    //x 位置
{
    int t=a[x],fa=x,child;
    while(fa*2<=l)
    {
        child=fa*2;
        if(child+1<=l&&a[child+1]<a[child]) child++;
        if(a[child]<t)
        {
            a[fa]=a[child];
            fa=child;
        }
        else break;
    }
    a[fa]=t;
}

void heap_build()
{
    int i;
    for(i=l/2; i>0; i--)
        heap_adjust(i);
}

long long heap_delmin()
{
    long long t=a[1];
    a[1]=a[l];
    l--;
    heap_adjust(1);
    return t;
}
int main()
{
    freopen("in.txt","r",stdin);
    int N;
    while(scanf("%d",&N)!=EOF)
    {
        long long i,t,m,n;
        long long sum=0;
        l=0;
        for(i=1; i<=N; i++)
        {
            scanf("%lld",&a[i]);
            //l=N;
            heap_add(a[i]);
        }
        //heap_build();
        for(i=0; i<N-1; i++)
        {
            m=heap_delmin();
            n=heap_delmin();
            sum+=m+n;
            heap_add(m+n);
        }
        printf("%I64d\n",sum);
    }
    return 0;
}

当然也可以用优先队列 =。= 省事了

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#define INF 0x3f3f3f3f
using namespace std;
int main()
{
    freopen("in.txt","r",stdin);
    int N;
    while(scanf("%d",&N)!=EOF)
    {
        priority_queue <int,vector<int>,greater<int> > q;
        long long i,t,a,b,s=0;
        for(i=0; i<N; i++)
        {
            scanf("%d",&t);
            q.push(t);
        }
        while(q.size()>1)
        {
            a=q.top();
            q.pop();
            b=q.top();
            q.pop();
            s+=a+b;
            q.push(a+b);
        }
        printf("%I64d\n",s);
    }
    return 0;
}



你可能感兴趣的:(哈夫曼树)