题解 P1090 【合并果子】

· · 题解

这道题我用的是 \color{pink}\colorbox{p}{优先队列+贪心}

那这道题该怎么贪呢,因为多多消耗的体力等于两堆果子的重量之和,所以我们要避免合重量大的果子,所以我们每次只需合重量最小果堆和重量第二小的果堆,这就需要用优先队列(其实是我懒
\color{red}\colorbox{y}{看代码(竞赛党码风)}
#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
int ans,n;
struct no
{
    int t;
    friend bool operator < (const no a,const no b)//优先队列( 不知道还有没有其他写法,我教练教我的这种写法 
    {
        return a.t>b.t;//优先队列里面要倒着写(虽然我也不知道为什么 
    }
};
priority_queue<struct no> a;//优先队列每次进元素都是要排序的,一定保证从小到大 
int main()
{
    cin>>n;
    for(int i=1;i<=n;++i)
    {
        struct no now;
        scanf("%d",&now.t);//纯粹是心理阴影//有一次交题,没看数据用cin,TLE 得我头皮发麻
        a.push(now);
    }
    for(int i=1;i<n;i++)
    {
        struct no now;
        struct no next;
        now=a.top();//因为用了优先队列队头一定是最小的,这里是取第一小的; 
        a.pop();
        next.t=now.t;
        now=a.top();//取第二小的 
        a.pop();
        next.t+=now.t;
        a.push(next);//合堆,再放进去 
        ans+=next.t;
    }
    cout<<ans;  
} 

\color{green}\colorbox{p}{希望da lao喜欢}

\color{white}\colorbox{p}{点个赞QWQ}