• 洛谷P1090 合并果子


    题目描述

    在一个果园里,多多已经将所有的果子打了下来,而且按果子的不同种类分成了不同的堆。多多决定把所有的果子合成一堆。

    每一次合并,多多可以把两堆果子合并到一起,消耗的体力等于两堆果子的重量之和。可以看出,所有的果子经过n-1次合并之后,就只剩下一堆了。多多在合并果子时总共消耗的体力等于每次合并所耗体力之和。

    因为还要花大力气把这些果子搬回家,所以多多在合并果子时要尽可能地节省体力。假定每个果子重量都为1,并且已知果子的种类数和每种果子的数目,你的任务是设计出合并的次序方案,使多多耗费的体力最少,并输出这个最小的体力耗费值。

    例如有3种果子,数目依次为1,2,9。可以先将1、2堆合并,新堆数目为3,耗费体力为3。接着,将新堆与原先的第三堆合并,又得到新的堆,数目为12,耗费体力为12。所以多多总共耗费体力=3+12=15。可以证明15为最小的体力耗费值。

    输入输出格式

    输入格式:

    输入文件fruit.in包括两行,第一行是一个整数n(1<=n<=10000),表示果子的种类数。第二行包含n个整数,用空格分隔,第i个整数ai(1<=ai<=20000)是第i种果子的数目。

    输出格式:

    输出文件fruit.out包括一行,这一行只包含一个整数,也就是最小的体力耗费值。输入数据保证这个值小于2^31。

    输入输出样例

    输入样例#1:
    3 
    1 2 9 
    
    输出样例#1:
    15
    

    说明

    对于30%的数据,保证有n<=1000:

    对于50%的数据,保证有n<=5000;

    对于全部的数据,保证有n<=10000。

    屠龙宝刀点击就送1

    屠龙宝刀点击就送2

    priority做法 35ms 383B

    #include <algorithm>
    #include <iostream>
    #include <queue>
    
    using namespace std;
    
    priority_queue<int,vector<int>,greater<int> >q;
    int n,a,h=0;
    int main()
    {
        cin>>n;
        while(n--)
        {
            cin>>a;
            q.push(a);
        }
        while(q.size()!=1)
        {
            int ans=0;
            int r=q.top() ;
            q.pop();
            ans+=r;
            r=q.top() ;
            q.pop();
            ans+=r;
            q.push(ans);
            h+=ans;
        }
        cout<<h;
    }
    View Code

    堆做法 18ms 785B

    #include <algorithm>
    #include <cstdio>
    
    using namespace std;
    
    int n,i,j,a,size,heap[10000*4+1];
    void heap_push(int n)
    {
        heap[++size]=n;
        int pos=size;
        while(pos>1)
        {
            int next=pos/2;
            if(heap[next]<heap[pos]) break;
            swap(heap[next],heap[pos]);
            pos=next;
        }
    }
    
    void heap_pop()
    {
        heap[1]=heap[size--];
        int pos=1;
        while(pos*2<=size)
        {
            int next=pos*2;
            if(heap[next]>heap[next+1])
            next++;
            if(heap[next]>=heap[pos]) break;
            swap(heap[next],heap[pos]);
            pos=next;
        }
    }
    int main()
    {
        scanf("%d",&n);
        for(i=1;i<=n;++i)
        {
            scanf("%d",&a);
            heap_push(a);
        }
        int ans=0;
        while(size>1)
        {
            int h=0;
            h+=heap[1];
            heap_pop();
            h+=heap[1];
            heap_pop();
            heap_push(h);
            ans+=h;
        }
        printf("%d",ans);
        return 0;
    }
    View Code
    我们都在命运之湖上荡舟划桨,波浪起伏着而我们无法逃脱孤航。但是假使我们迷失了方向,波浪将指引我们穿越另一天的曙光。
  • 相关阅读:
    链接脚本语法
    STM32 硬件IIC接口总线
    C99一些特性
    oneid与用户标签之间的相互打通 实现用户标签
    图计算实现ID_Mapping、Oneid打通数据孤岛
    对于hive使用的一点记录
    centos7 hue安装
    Kafka监控安装
    hadoop2.6.0集群搭建
    centos6+cdh5.4.0 离线搭建cdh搭建
  • 原文地址:https://www.cnblogs.com/ruojisun/p/6486535.html
Copyright © 2020-2023  润新知