fork download
  1. #include<bits/stdc++.h>
  2. #define int long long int
  3. using namespace std;
  4.  
  5. void solve(){
  6.  
  7. int n;
  8. cin>>n;
  9. while(true){
  10. int a[n];
  11. for(int i=0;i<n;i++) cin>>a[i];
  12. vector<pair<int,int> > buy;
  13. vector<pair<int,int> > sell;
  14. for(int i=0;i<n;i++){
  15. if(a[i]>0) buy.push_back({a[i],i});
  16. else sell.push_back({a[i],i});
  17. }
  18. int ans = 0;
  19. int i=0,j=0;
  20. while(i<buy.size() and j<sell.size()){
  21. int x = min(buy[i].first,-sell[j].first);
  22. buy[i].first -= x;
  23. sell[j].first += x;
  24. int diff = abs(buy[i].second - sell[j].second);
  25. ans += (x * diff);
  26. if(buy[i].first == 0) i++;
  27. if(sell[j].first == 0) j++;
  28. }
  29. cout<<ans<<endl;
  30. cin>>n;
  31. if(n==0) break;
  32. }
  33. }
  34.  
  35. int32_t main()
  36. {
  37. ios_base::sync_with_stdio(false);
  38. cin.tie(NULL);
  39.  
  40. solve();
  41.  
  42.  
  43. return 0;
  44. }
  45.  
  46.  
  47.  
  48.  
Success #stdin #stdout 0.01s 5280KB
stdin
5
5 -4 1 -3 1
6
-1000 -1000 -1000 1000 1000 1000
0
stdout
9
9000