zcmu-1810: Huffuman树(vector入门)

Description

Huffman树在编码中有着广泛的应用。在这里,我们只关心Huffman树的构造过程。   给出一列数{pi}={p0,  p1,  …,  pn-1},用这列数构造Huffman树的过程如下:   

1.  找到{pi}中最小的两个数,设为pa和pb,将pa和pb从{pi}中删除掉,然后将它们的和加入到{pi}中。这个过程的费用记为pa  +  pb。   

2.  重复步骤1,直到{pi}中只剩下一个数。   在上面的操作过程中,把所有的费用相加,就得到了构造Huffman树的总费用。   

本题任务:对于给定的一个数列,现在请你求出用该数列构造Huffman树的总费用。   例如,对于数列{pi}={5,  3,  8,  2,  9},Huffman树的构造过程如下:   

1.  找到{5,  3,  8,  2,  9}中最小的两个数,分别是2和3,从{pi}中删除它们并将和5加入,得到{5,  8,  9,  5},费用为5。   

2.  找到{5,  8,  9,  5}中最小的两个数,分别是5和5,从{pi}中删除它们并将和10加入,得到{8,  9,  10},费用为10。   

3.  找到{8,  9,  10}中最小的两个数,分别是8和9,从{pi}中删除它们并将和17加入,得到{10,  17},费用为17。   

4.  找到{10,  17}中最小的两个数,分别是10和17,从{pi}中删除它们并将和27加入,得到{27},费用为27。   5.  现在,数列中只剩下一个数27,构造过程结束,总费用为5+10+17+27=59。

Input

输入的第一行包含一个正整数n(n< =100)。   接下来是n个正整数,表示p0, p1, …, pn-1,每个数不超过1000。

Output

 输出用这些数构造Huffman树的总费用。

Sample Input

5 5 3 8 2 9

Sample Output

59

题目实则跟哈夫曼树没半毛钱关系哟,用下vector就好啦,要注意的是因为是要求剩下一个数的时候的总费用,n个数循环n - 1次就好了。

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
using namespace std;
int main(){
    vector<int> a;
    int n,p,total = 0;
    cin>>n;
    for(int i = 0 ; i < n;i++)
    {
        cin>>p;
        a.push_back(p);
    }
    int c = n - 1;
    while(c--)
    {
        int sum = 0;
        sort(a.begin(),a.end());
        vector<int>::iterator k = a.begin();
        sum += *k;
        a.erase(a.begin());
        sum += *k;
        a.erase(a.begin());
        total += sum;
        a.push_back(sum);
    }
    cout<<total<<endl;
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hzyhfxt/article/details/82457967