Huffman coding —— 贪心+优先队列

优先队列重载的用法

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include<string.h>
#include<cmath>
#include<stack>
#include<queue>

using namespace std;

struct node
{
    int weight;
    friend bool operator <(node a,node b)
    {
        return a.weight>b.weight;
    }
};

int main()
{
    ios::sync_with_stdio(false);cin.tie(0);

    int n,k;
    cin>>n;
    node left,right;
    priority_queue<node> q;
    int sum=0;
    while(n--)
    {
        node t;
        cin>>k>>t.weight;
        q.push(t);
    }
    while(q.size()!=1)
    {
        left=q.top();
        q.pop();
        right=q.top();
        q.pop();
        left.weight+=right.weight;
        sum+=left.weight;
        q.push(left);
    }
    printf("%d\n",sum);
    return 0;
}
/*
input

5
0 5
1 4
2 6
3 2
4 3

output

45

*/

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/79991101
今日推荐