UVa 10954 - Add All
2014-06-06 20:53
141 查看
传送门UVa 10954 - Add All
题意:找出最小的sum,使过程和最小。
一开始我把它们从小到大排序,认为这样就最小了。。但是我没有考虑例如这样的数据:
6 6 7 11.
一直加下去是61,而如果先加前两个,再加7和11,最后加剩下的两个,这样算出来是60。
原因就是当加上前两个数字之后,变成了7 11 12,这时候应该加7和11的,而我加了7和12,此处多了1.
然后就是上优先队列了。。
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
int main()
{
//freopen("input.txt", "r", stdin);
priority_queue<int, vector<int>, greater<int> > qu;
int n, i, j, temp;
while (scanf("%d", &n), n)
{
while (!qu.empty())
qu.pop();
for (i = 0; i < n; i++)
{
scanf("%d", &temp);
qu.push(temp);
}
int sum = 0;
while (qu.size() != 1)
{
int t = qu.top();
qu.pop();
int k = qu.top();
qu.pop();
sum += k + t;
qu.push(k + t);
}
printf("%d\n", sum);
}
return 0;
}
题意:找出最小的sum,使过程和最小。
一开始我把它们从小到大排序,认为这样就最小了。。但是我没有考虑例如这样的数据:
6 6 7 11.
一直加下去是61,而如果先加前两个,再加7和11,最后加剩下的两个,这样算出来是60。
原因就是当加上前两个数字之后,变成了7 11 12,这时候应该加7和11的,而我加了7和12,此处多了1.
然后就是上优先队列了。。
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
int main()
{
//freopen("input.txt", "r", stdin);
priority_queue<int, vector<int>, greater<int> > qu;
int n, i, j, temp;
while (scanf("%d", &n), n)
{
while (!qu.empty())
qu.pop();
for (i = 0; i < n; i++)
{
scanf("%d", &temp);
qu.push(temp);
}
int sum = 0;
while (qu.size() != 1)
{
int t = qu.top();
qu.pop();
int k = qu.top();
qu.pop();
sum += k + t;
qu.push(k + t);
}
printf("%d\n", sum);
}
return 0;
}
相关文章推荐
- uva 10954 Add All
- UVa 10954 (Huffman 优先队列) Add All
- uva 10954——Add All
- UVa 10954 Add All(优先队列)
- UVa 10954 - Add All(最优二叉树)
- uva 10954 add all
- UVa 10954 Add All 贪心
- UVA 10954 - Add All
- uva10954 - Add All
- UVA 10954 Add All
- UVa 10954,Add All
- UVa 10954 - Add All
- uva 10954 - Add All
- UVA-10954 Add All
- UVa 10954 Add All ——优先队列
- uva 10954 Add All
- UVA 10954 Add All (贪心 + 优先队列)
- uva 10954 Add All(哈弗曼编码)
- Add All - UVa 10954 优先队列
- UVA 10954 Add All 全部相加 (Huffman编码)