1.题目描述:点击打开链接
2.解题思路:根据题意描述,可以选择如下贪心策略:每次都选择两个比较小的数,相加后的结果放回队列中,而取最小值出列正好可以运用STL的priority_queue
3.代码:
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<algorithm> #include<string> #include<sstream> #include<set> #include<vector> #include<stack> #include<map> #include<queue> #include<deque> #include<cstdlib> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #include<functional> using namespace std; int main() { int n; while (scanf("%d", &n) == 1 && n) { priority_queue<int, vector<int>, greater<int> >q; int x; for (int i = 0; i < n; i++) { scanf("%d", &x); q.push(x); } int ans = 0; for (int i = 0; i < n - 1; i++) { int a = q.top(); q.pop(); int b = q.top(); q.pop(); ans += a + b; q.push(a + b); } printf("%d\n", ans); } return 0; }