zoukankan      html  css  js  c++  java
  • luoguP1090 合并果子 (贪心+优先队列)

    题目链接:https://www.luogu.org/problemnew/show/P1090

    思路:

    典型的贪心题,显然每次选择两个最小的堆合并最后耗费的体力最少,但每次合并之后都需要寻找最小的两个堆。假如每次合并之后都排一次序,一定会超时的。

    可以有很多实现方法,一种是使用优先队列,每次出队两个最小的,合并后入队。

    代码如下:

     1 #include<cstdio>
     2 #include<queue>
     3 #include<algorithm>
     4 using namespace std;
     5 
     6 int n;
     7 priority_queue<int,vector<int>,greater<int> > pq;
     8 int res=0;
     9 
    10 int main(){
    11     scanf("%d",&n);
    12     int x,tmp1,tmp2;
    13     for(int i=0;i<n;i++){
    14         scanf("%d",&x);
    15         pq.push(x);
    16     }
    17     for(int i=1;i<n;i++){
    18         tmp1=pq.top();
    19         pq.pop();
    20         tmp2=pq.top();
    21         pq.pop();
    22         res+=(tmp1+tmp2);
    23         pq.push(tmp1+tmp2);
    24     }
    25     printf("%d
    ",res);
    26     return 0;
    27 }
  • 相关阅读:
    ICMP协议
    观察者模式-Observer
    模板方法模式-Template Method
    Java的演变过程
    汉诺塔-Hanoi
    外观模式-Facade
    JDK5-增强for循环
    JDK5-可变参数
    动态代理与AOP
    代理模式-Proxy
  • 原文地址:https://www.cnblogs.com/FrankChen831X/p/10343136.html
Copyright © 2011-2022 走看看