zoukankan      html  css  js  c++  java
  • 求解哈夫曼树

    求集合K中权值最小的两个元素,使用堆数据结构。O(logn)。绕过对堆的实现。使用标准模板库中的--优先队列。

    #include<queue> using namespace std;

    priority_queue<int> Q; //建立的是最大堆; priority_queue<int,vector<int>,greater<int>> Q; //建立的是最小堆;

    将元素x放入堆中:Q.push(x);

    取出堆顶元素:int a = Q.top();

    弹出堆顶元素:Q.pop();

    #include<queue>
    #include<stdio.h>
    using namespace std;
    
    priority_queue<int,vector<int>,greater<int> > Q;
    
    int main()
    {
    	int n;
    	while(scanf("%d",&n)!=EOF)
    	{
    		while(Q.empty()==false) 
    			Q.pop(); //清空Q中的元素
    		for(int i=1;i<=n;i++)
    		{
    			int x;
    			scanf("%d",&x);
    			Q.push(x);
    		}
    		int ans = 0;
    		while(Q.size()>1){
    			int a = Q.top();
    			Q.pop();
    			int b = Q.top();
    			Q.pop();
    			ans += a + b;
    			Q.push(a+b);
    		}
    		printf("%d
    ",ans);
    	}
    	return 0;
    }
    
  • 相关阅读:
    ICMP协议
    观察者模式-Observer
    模板方法模式-Template Method
    Java的演变过程
    汉诺塔-Hanoi
    外观模式-Facade
    JDK5-增强for循环
    JDK5-可变参数
    动态代理与AOP
    代理模式-Proxy
  • 原文地址:https://www.cnblogs.com/rickhsg/p/3650132.html
Copyright © 2011-2022 走看看