有两种方法 一种是队列 一种是优先队列(priority_queue)
这两种方法的区别是队列定义时没有自动排序 所以只能在输入的时候按顺序才能输出正解(所以队列的方法不被认为是正解) 下面是代码 比较简便:
#include<bits/stdc++.h>
using namespace std;
queue<int>q;
int main() {
int n,x;
cin>>n;
for(int i=0;i<n;i++) {
cin>>x;
q.push(x);
}
int ans=0;
for(int i=1;i<n;i++) {
ans+=q.front();
q.pop();
ans+=q.front();
q.pop();
q.push(ans);
}
cout<<ans;
}
但是如果用了优先队列的话,刚开始就给你的是一个大根堆(从大到小排序)如果想让这个队列等价于一个小根堆,就可以入队的时候加一个负号,eg:(-1 -2 -9)这样就会按照绝对值从小到大排列 于是计数的时候用ans减去q.top()就ok了 然后这时候需要一个tmp来记录下来合并果子的和,然后将合并后的果子放到队尾 代码实现:
#include<bits/stdc++.h>
using namespace std;
priority_queue<int>q;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,x;
cin>>n;
for(int i=0;i<n;i++) {
cin>>x;
q.push(-x);
}
int ans=0,tmp;
while(q.size()>1) {
tmp=q.top();
ans-=q.top();
q.pop();
tmp+=q.top();
ans-=q.top();
q.pop();
q.push(tmp);
}
cout<<ans;
}
前几行是关闭同步,可以加速。 while的地方可以改写成for循环的形式:
#include<bits/stdc++.h>
using namespace std;
priority_queue<int>q;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,x;
cin>>n;
for(int i=0;i<n;i++) {
cin>>x;
q.push(-x);
}
int ans=0,tmp;
for(int i=1;i<n;i++){
tmp=q.top();
ans-=q.top();
q.pop();
tmp+=q.top();
ans-=q.top();
q.pop();
q.push(tmp);
}
cout<<ans;
}
就是这样