Yup!! The problem name reflects your task; just add a set of numb ers. But you may feel yourselves
condescended, to write a C/C++ program just to add a set of numb ers. Such a problem will simply
question your erudition. So, lets add some flavor of ingenuity to it.
Addition op eration requires cost now, and the cost is the summation of those two to b e added. So,
to add 1 and 10, you need a cost of 11. If you want to add 1, 2 and 3. There are several ways
1 + 2 = 3, cost = 3 1 + 3 = 4, cost = 4 2 + 3 = 5, cost = 5
3 + 3 = 6, cost = 6 2 + 4 = 6, cost = 6 1 + 5 = 6, cost = 6
Total = 9 Total = 10 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
3
1 2 3
4
1 2 3 4
0
Sample Output
9
19
题意yy很久,明白后又逗了个逼,弱智的直接挨个相加了,也没写几组多点的数据自己算一下,结果Nwa。。。
思路:每次选择最小的两个数相加,这两个数删除,其和插入,直到进行剩最后一个数,算是贪心吧,可以选用优先队列方便的实现取插操作
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <queue>
using namespace std;
typedef long long ll;
struct note
{
ll x;
bool operator < (const note &tmp)const
{
return x>tmp.x;
}
};
priority_queue <note> q;
int main()
{
freopen("in.txt","r",stdin);
int n;
while(scanf("%d",&n)!=EOF&&n)
{
while(!q.empty())
q.pop();
note tmp;
ll a;
for(int i=0;i<n;i++)
{
scanf("%lld",&a);
tmp.x=a;
q.push(tmp);
}
ll sum=0;
while(!q.empty())
{
note aa=q.top();q.pop();
if(q.empty())
break;
note bb=q.top();q.pop();
note cc;
cc.x=aa.x+bb.x;
sum+=cc.x;
q.push(cc);
}
printf("%lld\n",sum);
}
}