vjudge 贪心+分治专题-N题
来源:互联网 发布:我知道远程监控的域名 编辑:程序博客网 时间:2024/06/05 04:25
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 simplyquestion your erudition. So, lets 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 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
解决方案:一开始思路就有点错了,要先加最小的那两个,然后这两个数就替换成了两者之和,再从新的数组里寻找两个最小的。
如果每次都对新的数组排序的话,会很耗时,所以可用优先队列。
1.优先队列:#include <cstdio> #include <cstring> #include <queue> #include <vector> #include <algorithm> using namespace std; struct cmp{ bool operator()(int x,int y) { return x>y; //从小到大排序。即x小的优先级高。 } }; int main() { int n; while(scanf("%d",&n) != EOF && n) { priority_queue<int,vector<int>,cmp>q; // priority_queue<int,vector<int>,greater<int> > q; int num; for(int i = 0; i < n; i++) { scanf("%d",&num); q.push(num); } int cost,sum = 0; int tmp1,tmp2; while(q.size() >= 2) { tmp1 = q.top(); q.pop(); tmp2 = q.top(); q.pop(); cost = tmp1 + tmp2; sum += cost; q.push(cost); } printf("%d\n",sum); } return 0; } 2.每次sort排序:#include<stdio.h>#include<algorithm>using namespace std;int main(){int n,sum1;int a[50010];int b[50010];while(scanf("%d",&n),n){sum1=0;for(int i=0;i<n;i++){scanf("%d",&a[i]);}int cnt=0,cnt2=0;while(cnt<n-1){sort(a+cnt,a+n);a[cnt+1]+=a[cnt];b[cnt2++]=a[cnt+1];cnt++;}for(int i=0;i<cnt2;i++){sum1+=b[i];}printf("%d\n",sum1);}return 0;}
阅读全文
0 0
- vjudge 贪心+分治专题-N题
- vjudge上的专题
- 贪心专题16题
- 分治专题
- Vjudge
- 贪心小结 [贪心专题16题]
- 分治+贪心
- 贪心专题
- 贪心专题
- 贪心专题
- [HDOJ 4812][Vjudge 48318] D Tree [树的分治]
- 分治法专题
- cdq分治专题
- 贪心小结 [贪心专题16题] --Orz爱神
- 【贪心例题专题】&贪心~越多越好哟~&
- 关于分治的入门专题
- 贪心专题总结
- 贪心算法专题总结
- HttpClient
- 进程与线程(Java多线程总结一)
- MySQL(二)
- OR perceptron(感知机 )
- 事件对象
- vjudge 贪心+分治专题-N题
- hdu 2079
- 029 JDBC 开发
- tensorflow Examples:<3>实现自编码
- NOIP 2015 Day 2 stone 跳石头(二分)
- APP测试基本流程及测试内容
- JS的基础语法一
- java基础知识
- Oracle自学