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 }
  • 相关阅读:
    hdu 4597 记忆化搜索
    hdu 4494 最小费用流
    hdu 4598 差分约束
    poj 3621 0/1分数规划求最优比率生成环
    poj 1695 动态规划
    noi 97 积木游戏
    hdu 4705 排列组合
    洛谷P2014 选课
    洛谷P1776 宝物筛选
    洛谷P1782 旅行商的背包
  • 原文地址:https://www.cnblogs.com/Kiven5197/p/5523726.html
Copyright © 2011-2022 走看看