fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct P {
  4. int value;
  5. int accumulated;
  6. };
  7. stack<P> A, B;
  8. P merge(P x, P y){ // x is on top of y
  9. x.accumulated = max(x.accumulated, y.accumulated);
  10. return x;
  11. }
  12. void push(int value){
  13. P element;
  14. element.value = element.accumulated = value;
  15. if(!B.empty())
  16. element = merge(element, B.top());
  17. B.push(element);
  18. }
  19. void pop(){
  20. if(A.empty()){
  21. while(!B.empty()){
  22. P element = B.top();
  23. B.pop();
  24. element.accumulated = element.value;
  25. if(!A.empty())
  26. element = merge(element, A.top());
  27. A.push(element);
  28. }
  29. }
  30. A.pop();
  31. }
  32. int get_max(){
  33. int mx = -(1<<30);
  34. if(!A.empty())
  35. mx = max(mx, A.top().accumulated);
  36. if(!B.empty())
  37. mx = max(mx, B.top().accumulated);
  38. return mx;
  39. }
  40. int main() {
  41. push(7);
  42. push(5);
  43. cout << get_max() << '\n';
  44. pop();
  45. cout << get_max() << '\n';
  46. push(12);
  47. cout << get_max() << '\n';
  48. pop();
  49. cout << get_max() << '\n';
  50. pop();
  51. push(13);
  52. push(15);
  53. pop();
  54. push(17);
  55. cout << get_max() << '\n';
  56. return 0;
  57. }
Success #stdin #stdout 0s 4520KB
stdin
Standard input is empty
stdout
7
5
12
12
17