fork download
  1. #include<iostream>
  2. #include<cstdio>
  3. using namespace std;
  4.  
  5. const int MAX_ALLOWED_SIZE = 1000000;
  6.  
  7. template <class T>
  8. class MyStack{
  9. T *a;
  10. int *min, *max;
  11. int top;
  12. int size;
  13.  
  14. public:
  15. MyStack(int s=MAX_ALLOWED_SIZE)
  16. {
  17. //this.size gives this error: request for member `size' in `this', which is of non-class type `MyStack* const'
  18. size = s;
  19. a = new T [size];
  20. min = new int [size];
  21. max = new int [size];
  22. top = -1;
  23. }
  24. void push(T i)
  25. {
  26. if(top == size-1)
  27. {
  28. cout<<"Overflow error"<<endl;
  29. }
  30.  
  31. //if stack has space
  32. else
  33. {
  34. if(top == -1)
  35. {
  36. top++;
  37. min[top] = top;
  38. max[top] = top;
  39. a[top] = i;
  40. }
  41. else if(i <= a[min[top]])
  42. {
  43. top++;
  44. min[top] = top;
  45. a[top] = i;
  46. max[top] = max[top-1];
  47. }
  48.  
  49. else if(i >= a[max[top]])
  50. {
  51. top++;
  52. min[top] = min[top-1];
  53. a[top] = i;
  54. max[top] = top;
  55. }
  56.  
  57. else
  58. {
  59. top++;
  60. min[top] = min[top-1];
  61. a[top] = i;
  62. max[top] = max[top-1];
  63. }
  64. }
  65. }
  66.  
  67. T pop()
  68. {
  69. if(stackEmpty())
  70. {
  71. cout<<"Underflow error"<<endl;
  72. return NULL;
  73. }else return a[top--];
  74. }
  75.  
  76. T maxm()
  77. {
  78. //cout<<"called"<<endl;
  79. if(!stackEmpty())
  80. {
  81. //cout<<max[top]<<" = " <<a[max[top]]<<endl;
  82. return a[max[top]];
  83. }
  84. cout<<"called\n";
  85. return NULL;
  86. }
  87.  
  88. T minm()
  89. {
  90. //cout<<"called"<<endl;
  91. if(!stackEmpty())
  92. {
  93. cout<<"a["<<min[top]<<"] = " <<a[min[top]]<<endl;
  94. return a[min[top]];
  95. }
  96. return NULL;
  97. }
  98.  
  99. T minmm()
  100. {
  101. cout<<"called\t";
  102. if(!stackEmpty())
  103. {
  104. cout<<"a["<<min[top]<<"] = " <<a[min[top]]<<endl;
  105. return a[min[top]];
  106. }
  107. return NULL;
  108. }
  109.  
  110. bool stackEmpty()
  111. {
  112. if(top == -1) return true;
  113. }
  114.  
  115. void printStack()
  116. {
  117. T s = top+1;
  118. while(s--)
  119. {
  120. printf("a[%d] = %d\n",s,a[s]);
  121. }
  122. }
  123. };
  124.  
  125. int main()
  126. {
  127. MyStack<int> s(5);
  128. int t;
  129.  
  130. while(true)
  131. {
  132. scanf("%d",&t);
  133. s.push(t);
  134. cout<<"min = "<<s.minm()<<endl;
  135. cout<<"min = "<<s.minmm()<<endl;
  136.  
  137. if(t==-1) break;
  138.  
  139. }
  140.  
  141. cout<<"----------"<<endl;
  142. s.printStack();
  143. }
Success #stdin #stdout 0s 2864KB
stdin
234
23
-1
stdout
min = 0
called	min = 0
min = 0
called	min = 0
min = 0
called	min = 0
----------
a[2] = -1
a[1] = 23
a[0] = 234