B - 树-堆结构练习——合并果子之哈夫曼树

初试堆的一系列操作

Problem Description

在一个果园里,多多已经将所有的果子打了下来,而且按果子的不同种类分成了不同的堆。多多决定把所有的果子合成一堆。
每一次合并,多多可以把两堆果子合并到一起,消耗的体力等于两堆果子的重量之和。可以看出,所有的果子经过n-1次合并之后,就只剩下一堆了。多多在合并果子时总共消耗的体力等于每次合并所消耗体力之和。
因为还要花大力气把这些果子搬回家,所以多多在合并果子时要尽可能地节省体力。假定每个果子重量都为1,并且已知果子的种类数和每种果子的数目,你的任务是设计出合并的次序方案,使多多耗费的体力最少,并输出这个最小的体力耗费值。
例如有3种果子,数目依次为1,2,9。可以先将1、2堆合并,新堆数目为3,耗费体力为3。接着,将新堆与原先的第三堆合并,又得到新的堆,数目为12,耗费体力为12。所以多多总共耗费体力=3+12=15。可以证明15为最小的体力耗费值。

Input

第一行是一个整数n(1<=n<=10000),表示果子的种类数。第二行包含n个整数,用空格分隔,第i个ai(1<=ai<=20000)是第i个果子的数目。

Output

输出包括一行,这一行只包含一个整数,也就是最小的体力耗费值。输入数据保证这个值小于2^31。

Sample Input

3
1 2 9

Sample Output

15

#include <stdio.h>
#include <stdlib.h>

void Sort_MinHeap(struct Heap *heap, int i);
void Insert_Heap(struct Heap *heap, int n);
int Delete_Heap(struct Heap *heap);
int Min(int a, int b);

struct Heap
{
    int *N;
    int Size;
}heap;

int main()
{
    int n, sum = 0;
    scanf("%d", &n);
    heap.N = (int *)malloc(10010 * sizeof(int));
    heap.Size = n;
    for(int i = 1; i <= n; i++)
        scanf("%d", &heap.N[i]);
    Sort_MinHeap(&heap, n/2);
    for(int i = 1; i < n; i++)
    {
        int t1 = Delete_Heap(&heap);
        int t2 = Delete_Heap(&heap);
        sum += t1 + t2;
        Insert_Heap(&heap, t1 + t2);
    }
    printf("%d\n", sum);
}
void Insert_Heap(struct Heap *heap, int n)
{
    heap->N[++heap->Size] = n;
    int num = heap->Size;
    while(n < heap->N[num/2] && num != 1)
    {
        heap->N[num] = heap->N[num/2];
        num /= 2;
    }
    heap->N[num] = n;
}
int Delete_Heap(struct Heap *heap)
{
    int re = heap->N[1];
    int t = heap->N[heap->Size--];
    int child = Min(2, 3), parent = 1;
    while(t > heap->N[child] && child <= heap->Size)
    {
        heap->N[parent] = heap->N[child];
        parent = child;
        child = Min(child*2, child*2+1);
    }
    heap->N[parent] = t;
    return re;
}
int Min(int a, int b)
{
    return (b <= heap.Size && heap.N[b] < heap.N[a]) ? b : a;
}
void Sort_MinHeap(struct Heap *heap, int i)
{
    for(; i >= 1; i--)
    {
        int child = Min(i*2, i*2+1);
        int t = heap->N[i], parent = i;
        while(t > heap->N[child] && child <= heap->Size)
        {
            heap->N[parent] = heap->N[child];
            parent = child;
            child = Min(child*2, child*2+1);
        }
        heap->N[parent] = t;

    }

猜你喜欢

转载自blog.csdn.net/qq_30351943/article/details/84981961