POJ3253

poj3253:[url]http://poj.org/problem?id=3253[/url],简单的哈夫曼问题

#include <iostream>
#include <fstream>
#include <queue>
using namespace std;

struct cmp
{
bool operator() (unsigned int x,unsigned int y)
{
return x>y;
}
};

priority_queue<unsigned int,vector<unsigned int>,cmp> q;
unsigned int ans=0;
unsigned int total=0;

void doit()
{
unsigned int sum=0;

while(!q.empty())
{
sum+=q.top();
q.pop();
if(!q.empty())
{
sum+=q.top();
q.pop();
if(sum!=total)
q.push(sum);
}
ans+=sum;
sum=0;
}
}

int main()
{
unsigned int n;
// ifstream cin("1.txt");
cin>>n;
if(1==n)
{
ans=0;
}
else
{
for(unsigned int i=0;i<n;i++)
{
unsigned int temp;
cin>>temp;
q.push(temp);
total+=temp;
}
doit();
}
cout<<ans<<endl;

return 0;
}


[size=large] 注意此题的数值范围,最后结果用unsigned int或long保存,不然会数据会溢出,另外,注意n=1时,花费为0。[/size]
[size=large]这里优先队列的用法,可以设置比较函数,重载()运算符,还有一种用来比较结构体的方法,重载>操作符。[/size]

struct node
{
int x, y;
friend bool operator < (node a, node b)
{
return a.x > b.x; //结构体中,x小的优先级高
}
};
priority_queue<node>q;//定义方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值