poj: 3253

时间:2023-03-09 06:33:53
poj: 3253

这题一开始从大往小考虑是行不通的,这个时候从小到大考虑就很容易了。用一个priority_queue选出两个最小的值加到结果里再推回queue里,直到queue空为止。注意这里res要用long long,否则会wa。

注意priority_queue默认是从大到小排,要从小到大排需要用greater<T>来规定,如果是自己定义的class,需要在class里定义cmp。

 #include <iostream>
 #include <queue>

 using namespace std;

 int main()
 {
     priority_queue<int, vector<int>, greater<int> > S;
     int n;
     cin >> n;
     long long w;
     ; i < n; i++) {
         cin >> w;
         S.push(w);
     }
     ;
     ;
     ) {
         tmp += S.top();
         S.pop();
         if (S.empty()) break;
         tmp += S.top();
         S.pop();
         if (S.empty()) break;
         res += tmp;
         S.push(tmp);
         tmp = ;
     }
     res += tmp;
     cout << res << endl;
     ;
 }