zoukankan      html  css  js  c++  java
  • UVa-10954

    10954 - Add All

    Time limit: 3.000 seconds

    Yup!! The problem name reflects your task; just add a set of numbers. But you may feel yourselves condescended, to write a C/C++ program just to add a set of numbers. Such a problem will simply question your erudition. So, let’s add some flavor of ingenuity to it.

    Addition operation requires cost now, and the cost is the summation of those two to be added. So, to add 1 and 10, you need a cost of 11.If you want to add 12 and 3. There are several ways –

    1 + 2 = 3, cost = 3

    3 + 3 = 6, cost = 6

    Total = 9

    1 + 3 = 4, cost = 4

    2 + 4 = 6, cost = 6

    Total = 10

    2 + 3 = 5, cost = 5

    1 + 5 = 6, cost = 6

    Total = 11

    I hope you have understood already your mission, to add a set of integers so that the cost is minimal.

    Input

    Each test case will start with a positive number, N (2 ≤ N ≤ 5000) followed by N positive integers (all are less than 100000). Input is terminated by a case where the value of N is zero. This case should not be processed.

    Output

    For each case print the minimum total cost of addition in a single line.

    样例输入:

    3

    1 2 3

    4

    1 2 3 4

    0

     

    样例输出:

    9

    19

    题意:

    给定n个数,任意两数相加的花费为相加的和,和放入队中继续相加,求全部加完时的最小值。

    定义优先队列最小值优先,队首两元素相加并分别出队,总值+=和,若队列此时不为空,则将和入队,继续循环直到队列为空。

    附AC代码:

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<algorithm>
     5 #include<queue>
     6 using namespace std;
     7 
     8 struct cmp{//重载“()”运算符,自定义最小值优先 
     9     bool operator()(int &a,int &b){
    10         return a>b;
    11     }
    12 };
    13 
    14 int n,a;
    15 
    16 int main(){
    17     priority_queue<int,vector<int>,cmp> q; //定义优先队列q 
    18     while(~scanf("%d",&n)&&n!=0){
    19         for(int i=0;i<n;i++){//入队 
    20             scanf("%d",&a);
    21             q.push(a);
    22         }
    23         int sum=0;
    24         while(q.size()){//当队列不为空时 
    25             int x=q.top();//最小的两个相加并出队 
    26             q.pop();
    27             int y=q.top();
    28             q.pop();
    29             sum+=x+y;//总和 
    30             if(q.size())//若加完队列不为空,则将和入队 
    31             q.push(x+y);
    32         }
    33         printf("%d
    ",sum);
    34     }
    35     return 0;
    36 }
  • 相关阅读:
    keepalive高可用集群(nginx)
    nginx负载均衡
    linux-------lnmp安装
    nginx编译安装
    Django+MySQL安装配置详解(Linux)[更新为1.8.2版]
    linux性能监控——CPU、Memory、IO、Network
    linux 时钟时间,用户CPU时间,系统CPU时间 .
    指针用作传出参数时,需要二级指针
    僵尸进程&孤儿进程
    XHProf是一个分层PHP性能分析工具。
  • 原文地址:https://www.cnblogs.com/Kiven5197/p/5523726.html
Copyright © 2011-2022 走看看