题解 | #[NOIP2004]合并果子#

[NOIP2004]合并果子

https://ac.nowcoder.com/acm/problem/16663

思路

贪心正解。用优先队列,每次把最小的两个果子合并了,得到的是最优解。

代码

#include<bits/stdc++.h>
using namespace std;

priority_queue<int,vector<int> , greater<int> >q;
int n,a,b,ans=0;

int main(){
     scanf("%d",&n);
     for(int i=1;i<=n;i++){
         scanf("%d",&a);
         q.push(a);
    }
    while(q.size()!=1){
        a=q.top();
        q.pop();
        b=q.top();
        q.pop();
        ans+=a+b;
        q.push(a+b);
    }
    printf("%d",ans);
    return 0;   
}
全部评论

相关推荐

评论
2
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务