zoukankan      html  css  js  c++  java
  • CodeVS 1063 合并果子

    题目描述 Description

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

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

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

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

    输入描述 Input Description

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

    输出描述 Output Description

    输出包括一行,这一行只包含一个整数,也就是最小的体力耗费值。输入数据保证这个值小于231。

    样例输入 Sample Input


    1 2 9

    样例输出 Sample Output

    15

    数据范围及提示 Data Size & Hint

    对于30%的数据,保证有n<=1000: 
    对于50%的数据,保证有n<=5000; 
    对于全部的数据,保证有n<=10000。

    堆结构的上手测试题。

    之前学堆的时候写过一个模板,直接拿过来用。

    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    int heap[20010] , temp ,size , ans , n , a , b;
    void Insert(int x){
        int curr = ++size;
        heap[size] = x;
        int parent = curr / 2;
        while(parent > 0 && heap[parent] > heap[curr]){
            swap(heap[parent] , heap[curr]);
            curr = parent;
            parent = curr / 2;
        }     
    }
    void Pop(){
        heap[1] = heap[size--];
        int curr = 1;
        int son = curr * 2;
        if(heap[son] > heap[son + 1])son++;
        while(son <= size && heap[son] < heap[curr]){
            swap(heap[son] , heap[curr]);
            curr = son;
            son = curr * 2;
            if(heap[son] > heap[son + 1])son++;
        }
    }

    每次把小根堆里最小的两个值Pop出来,再Insert二者的和,来模拟合并两堆果子。最后只剩一堆的时候停止。

    主函数:

    int main(){
        cin >> n;
        for(int i = 1 ; i <= n ; i++){
            cin >> temp;
            Insert(temp);
        }
        while(size > 1){
            a = heap[1];Pop();
            b = heap[1];Pop();
            temp = a + b;
            Insert(temp);
            ans += temp;
        }
        cout << ans << endl;
        return 0;
    }
  • 相关阅读:
    显示多行字符串
    dowhile
    获取系统的相关文件夹
    DLL 实际应用版本
    ShellExecute
    LoadLibrary
    MFC DLL的创建
    在DLL中存放资源
    替换字符串
    RemoveDirectoryB
  • 原文地址:https://www.cnblogs.com/miserweyte/p/11134368.html
Copyright © 2011-2022 走看看