POJ 3253 Fence Repair 优先队列

#include<stdio.h>
#include<iostream>
#include<queue>
/*
* 使用longlong保存结果
* 优先队列解决问题
* 哈夫曼树
*/
using namespace std;
priority_queue<int, vector<int>, greater<int> > pq;
int a[20005];
int main()
{
    int n;
    cin>>n;
    for(int i= 0 ; i < n ; i++)
    {
        scanf("%d",&a[i]);
        pq.push(a[i]);
    }
    long long anss = 0;
    int ans = pq.top();
    pq.pop();
    ans += pq.top();
    pq.pop();
    anss += ans;
    while(!pq.empty())
    {
        pq.push(ans);
        ans = pq.top();
        pq.pop();
        ans += pq.top();
        pq.pop();
        anss+=ans;
    }
    cout<<anss;


}
#include<stdio.h>
#include<iostream>
#include<queue>
/*
* 结构体类型优先队列直接通过friend关键字重载小于号
*/
using namespace std;
struct node
{
    friend bool operator < (node n1,node n2)
    {
        return n1.priority < n2.priority;
    }
    int priority;
    int value;
};
priority_queue <node> qn;//必须要重载运算符
int main()
{
    int i;
    node b[10];
    b[0].priority = 6; b[0].value = 1;
    b[1].priority = 9; b[1].value = 5;
    b[2].priority = 2; b[2].value = 3;
    b[3].priority = 8; b[3].value = 2;
    b[4].priority = 1; b[4].value = 4;
    for(i = 0; i < 5; i++)
        qn.push(b[i]);
    for(i = 0; i < 5; i++)
    {
        cout<<qn.top().priority<<'\t'<<qn.top().value<<endl;
        qn.pop();
    }
}



你可能感兴趣的:(POJ 3253 Fence Repair 优先队列)