http://ac.jobdu.com/problem.php?pid=1107
http://ac.jobdu.com/problem.php?pid=1172
代码差不多:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <stack>
#include <queue>
#define ISYEAP(x) x%100!=0 && x%4==0 || x%400==0 ? 1:0
using namespace std;
priority_queue<int,vector<int>,greater<int> > Q;
int thePath;
void input(int num){
int temp;
for(int i=0;i<num;i++){
cin>>temp;
Q.push(temp);
}
}
void haffman(int len){
int thefirst;
int thesecond;
thePath=0;
while(1){
if(Q.size()==1)
{
// thePath+=Q.top();
Q.pop();
break;
}
thefirst=Q.top();
Q.pop();
thesecond=Q.top();
Q.pop();
thePath+=thefirst+thesecond;
// cout<<"thefirst="<<thefirst<<endl;
// cout<<"thesecond="<<thesecond<<endl;
// cout<<"thePath="<<thePath<<endl;
Q.push(thefirst+thesecond);
}
cout<<thePath<<endl;
// Q.pop();
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
if(n==0){
return 0;
}
input(n);
haffman(n);
}
return 0;
}
priority_queue<int > Q;//最大堆
priority_queue<int,vector<int>,greater<int> >//最小堆,且最后两个>>必须分开写> >
优先队列:
其他人写的博客:
http://www.cnblogs.com/flyoung2008/articles/2136485.html
http://www.cnblogs.com/void/archive/2012/02/01/2335224.html