/ 科创班 /

记录详情

Accepted


  
# 状态 耗时 内存占用
#1 Accepted 4ms 360.0 KiB
#2 Accepted 5ms 380.0 KiB
#3 Accepted 3ms 384.0 KiB
#4 Accepted 3ms 360.0 KiB
#5 Accepted 3ms 360.0 KiB
#6 Accepted 2ms 276.0 KiB
#7 Accepted 2ms 376.0 KiB
#8 Accepted 2ms 256.0 KiB
#9 Accepted 8ms 364.0 KiB
#10 Accepted 8ms 372.0 KiB
#11 Accepted 2ms 368.0 KiB
#12 Accepted 2ms 340.0 KiB
#13 Accepted 2ms 356.0 KiB
#14 Accepted 2ms 380.0 KiB
#15 Accepted 1ms 356.0 KiB
#16 Accepted 2ms 360.0 KiB
#17 Accepted 2ms 364.0 KiB
#18 Accepted 2ms 376.0 KiB
#19 Accepted 2ms 356.0 KiB
#20 Accepted 4ms 364.0 KiB

代码

#include <iostream>
#include <iomanip>
using namespace std;


typedef struct
{
    int weight;    // 权值 
    int parent, lChild, rChild;    //父母节点,左孩子,右孩子 
}HTNode, *HuffmanTree;


// 选择权值最小的两颗树 
void SelectMin(HuffmanTree hT, int n, int &s1, int &s2)
{
    s1=s2=0;

    int i;
    for(i=1;i<n;++i)
	{
        if(hT[i].parent==0)
		{
            if(s1==0)
              s1=i;
            else
			{
              s2=i;
              break;
            }
        }
    }
    if(hT[s2].weight<hT[s1].weight)
	{
        int t;
		t=s1;
        s1=s2;
        s2=t;
    }

    for(i+=1;i<n;++i)
	{
        if(0==hT[i].parent)
		{
            if(hT[i].weight<hT[s1].weight)
			{
              s2=s1;
              s1=i;
            }
			else if(hT[i].weight<hT[s2].weight)
              s2=i;
        }
    }
}

// 构造有n个权值的哈夫曼树 
void CreateHufmanTree(HuffmanTree &hT)
{
    int n,m,i;
    cin >>n;
    m=2*n-1;

    hT=new HTNode[m+1];   
    for(i=1;i<=m;++i)
      hT[i].parent=hT[i].lChild=hT[i].rChild=0;
    for(i=1;i<=n;++i)
      cin>>hT[i].weight; // 输入权值 
    hT[0].weight=m;    // 用0号节点保存节点数量 

    for(i=n+1;i<=m;++i)
	{
        int s1,s2;
        SelectMin(hT,i,s1,s2);
        hT[s1].parent=hT[s2].parent=i;
        hT[i].lChild=s1; hT[i].rChild=s2;    // 作为新节点的孩子 
        hT[i].weight=hT[s1].weight+hT[s2].weight;    // 新节点为左右孩子节点权值之和 
    }
}

int HuffmanTreeWPL_(HuffmanTree hT, int i, int deepth)
{
    if(hT[i].lChild==0&&hT[i].rChild==0)
        return 
		  hT[i].weight*deepth;
    else
        return 
		  HuffmanTreeWPL_(hT,hT[i].lChild, deepth+1) + HuffmanTreeWPL_(hT,hT[i].rChild,deepth+1);
}

// 计算WPL(带权路径长度) 
int HuffmanTreeWPL(HuffmanTree hT)
{
    return HuffmanTreeWPL_(hT,hT[0].weight,0);
}

// 销毁哈夫曼树 
void DestoryHuffmanTree(HuffmanTree &hT)
{
    delete[] hT;
    hT=NULL;
}

int main()
{
    HuffmanTree hT;
    CreateHufmanTree(hT);
    cout<<HuffmanTreeWPL(hT)<<endl;
    DestoryHuffmanTree(hT);
    return 0;
}

信息

递交者
类型
递交
题目
哈夫曼树
题目数据
下载
语言
C++
递交时间
2018-05-15 20:28:19
评测时间
2018-05-15 20:28:19
评测机
分数
100
总耗时
69ms
峰值内存
384.0 KiB