fork(1) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main(){
  5. ios::sync_with_stdio(0);
  6. cin.tie(0);
  7. int n;
  8. cin >> n;
  9. vector<int> p(n);
  10. for(int i = 0; i < n; ++i){
  11. cin >> p[i];
  12. }
  13. long long ans = 0;
  14. priority_queue<pair<int,int>> pq;
  15. for(int i = n-1; i >= 0; --i){
  16. if(pq.empty()) pq.push({p[i],-1});
  17. else {
  18. if(pq.top().first > p[i]) {
  19. auto x = pq.top();
  20. pq.pop();
  21. ans += x.first - p[i];
  22. if(x.second != -1) {
  23. pq.push({x.first, -1});
  24. }
  25. pq.push({p[i],1});
  26. }
  27. else {
  28. pq.push({p[i],-1});
  29. }
  30. }
  31. }
  32. cout << ans << endl;
  33. }
Success #stdin #stdout 0s 15408KB
stdin
Standard input is empty
stdout
0