[贪心&&优先队列]uva10954 Add All

Problem F
Add All
Input:
 standard input
Output: standard output

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.

 

Sample Input                           Output for Sample Input

3

1 2 3

4

1 2 3 4

0

 

9

19

 

Problem setter: Md. Kamruzzaman, EPS


题意:在数组中拿出两个数相加,再把结果放回数组中再如此反复,求最小的结果是多少,典型的哈弗曼编码的题目。

思路:使用贪心策略,每次都在数组中取出最小的两个数相加,由此得到的结果最小。使用优先队列较为简单,我自己使用的是set。

set代码

#include<iostream>
#include<algorithm>
#include<iterator>
#include<set>

using namespace std;

multiset<int> vec;

bool cmp(int x,int y)
{
    return x>y;
}

int main()
{
    int num;
    while(cin>>num&&num)
    {
        int key;
        vec.clear();
        for(int i=0;i<num;i++)
        {
            cin>>key;
            vec.insert(key);
        }
        int sum=0;
        int x,y,s;
        while(vec.size()>=2)
        {
            multiset<int>::iterator it1=vec.begin();
            x=*it1;
            vec.erase(it1);
            multiset<int>::iterator it2=vec.begin();
            y=*it2;
            vec.erase(it2);
            sum=sum+x+y;
            vec.insert(x+y);
        }
        cout<<sum<<endl;
    }
    return 0;
}


优先队列代码:

#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

struct node {
    int x;
    bool operator < ( const node& a ) const {
        return x > a.x;
    }
}num;
int n, sum, tmp;

int main()
{
    while ( scanf("%d", &n) != EOF && n ) {
        sum = 0;
        priority_queue< node > pq;
        for ( int i = 0, x; i < n; ++i ) {
            scanf("%d", &num.x );
            pq.push(num);
        }
        while ( !pq.empty() ) {
            node n1, n2;
            n1 = pq.top(); pq.pop();
            n2 = pq.top(); pq.pop();
            tmp = n1.x + n2.x;
            sum += tmp;
            num.x = tmp;
            if ( !pq.empty() ) pq.push( num ); // 如果这时候,队列为空,则说明所有的数都加完了,每次出队两个,入队一个,最后一个不入队
        }
        printf("%d\n", sum);
    }
}


你可能感兴趣的:(优先队列,贪心)