UVA 10954 Add All 全加一起 模拟+贪心+优先队列

来源:互联网 发布:win10解压缩软件 编辑:程序博客网 时间:2024/05/14 14:47

题意:规定每次加法的运算量为加法的和,给你n个数,要你全部加起来,尽量让运算量为最小。

要让运算量最小,只要每次找最小的两个数加起来就行了,之后得把和放回数组重新排序。

数据量为5000×100000,5e+8,用int是可以的,但是我刚开始果断用的long long,然后A掉之后改成int型,顺便把cout改成printf,结果慢了3ms,还以为是cout在拖慢速度,网上查了一下,发现cout和printf差别不是很大。把类型改回long long后,用printf和用cout一样快。看来是类型的问题,难道long long的操作会比int快吗?当然也有可能是程序误差 = =。

关于数组的排序,我直接用STL,感觉优先队列好像会快点,于是写了,顺便复习一下。

代码:

 /* *   Author:        illuz <iilluzen@gmail.com> *   Blog:          http://blog.csdn.net/hcbbt *   File:          UVA10954.cpp *   Lauguage:      C/C++ *   Create Date:   2013-08-30 18:35:59 *   Descripton:    UVA 10954 Add All, greet  */#include <cstdio>#include <queue>using namespace std;#define rep(i, n) for (int i = 0; i < (n); i++)typedef long long LL;int n, t;priority_queue<int, vector<int>, greater<int> > a;LL sum;int main() {while (scanf("%d", &n) && n) {while (!a.empty()) a.pop();rep(i, n) {scanf("%d", &t);a.push(t);}sum = 0;rep(i, n - 1) {int ta = a.top();a.pop();int tb = a.top();a.pop();sum += ta + tb;a.push(ta + tb);}printf("%lld\n", sum);}return 0;}



原创粉丝点击