贪心策略:每次选取最小的两个数相加,将和作为新的数加入序列,再从里面取两个最小的数...直到只剩下一个数。优先队列正好对付这题。
PS :以前在学校OJ做过几乎一毛一样的这题
AC代码:
#include<cstdio>
#include<queue>
using namespace std;
priority_queue<int, vector<int>, greater<int> >Q; //the smallest is on top
int main(){
int n;
while(scanf("%d",&n)==1 && n) {
int x;
for(int i = 0; i < n; ++i){
scanf("%d",&x);
Q.push(x);
}
int ans = 0;
while(Q.size() > 1){
int x = Q.top(); Q.pop();
int y = Q.top(); Q.pop();
ans += x + y;
Q.push(x + y);
}
printf("%d\n",ans);
// clean
while(!Q.empty()) Q.pop();
}
return 0;
}
如有不当之处欢迎指出!