链接:https://www.luogu.org/problemnew/show/P1090
思路:每次取最小的两堆合并,做法是每次合并完排序,取最小的两个,优先队列由于每次push后是自动排序,所以用优先队列写很方便
代码:
1 #include<bits/stdc++.h> 2 #define inf 0x3f3f3f3f 3 typedef long long ll; 4 const int M = int(1e5)*2 + 5; 5 using namespace std; 6 int n; 7 ll ans = 0; 8 priority_queue<int, vector<int>, greater<int> >q; 9 10 int main() 11 { 12 cin >> n; 13 for (int i = 0, x; i < n; i++) cin >> x, q.push(x); 14 while (q.size() >= 2) 15 { 16 int a = q.top(); q.pop(); 17 int b = q.top(); q.pop(); 18 ans += (a + b); 19 q.push(a + b); 20 } 21 cout << ans << endl; 22 return 0; 23 }
备注:用优先队列写就是道水题,虽然在这之前我完全不会用orz。看了这篇博客后我顿悟了->这篇,总结得很好