题解:P1090 [NOIP 2004 提高组] 合并果子

· · 题解

思路

考虑贪心策略,每次选择最小的两堆果子合并在一起,直到只剩下一堆,过程中的体力消耗就是答案。
本题可以使用 STL 中的优先队列(priority_queue)求解,也可以手写堆,此处不展示手写堆。

优先队列介绍

dalao 请跳过 ~dalao 估计是不会来看这篇题解的~。

头文件

#include <queue> //使用万能头的人当我没说

定义

大根堆

priority_queue<int> c;  

小根堆

priority_queue<int,vector<int>,greater<int> > c;

插入

c.push();   

访问堆顶元素

c.top();

弹出堆顶元素

c.pop();

判空

c.empty();  

代码

你们最喜欢的代码来了!!!

#include<bits/stdc++.h>
using namespace std;
priority_queue<int,vector<int>,greater<int> > c;
int n,x,y,ans;
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)cin>>x,c.push(x);
    while(c.size()>1)
    {
        x=c.top();
        c.pop();
        y=c.top();
        c.pop();
        c.push(x+y);
        ans+=x+y;
    }
    cout<<ans;
    return 0;
 }