1 #include <bits/stdc++.h> 2 using namespace std; 3 4 class minStack{ 5 private: 6 stack<int> s; 7 stack<int> mins; 8 public: 9 void push(int x){ 10 s.push(x); 11 if(mins.empty()==true || mins.top()>=x) 12 mins.push(x); 13 } 14 15 int getMin(){ 16 return mins.top(); 17 } 18 19 void pop(){ 20 int temp = s.top(); 21 s.pop(); 22 if(temp == mins.top()) 23 mins.pop(); 24 } 25 }; 26 27 int main(){ 28 int N; 29 cin>>N; 30 minStack ms; 31 for(int i=0;i<N;++i){ 32 string s = ""; 33 cin>>s; 34 if(s == "push"){ 35 int num; 36 cin>>num; 37 ms.push(num); 38 } 39 else if(s == "pop"){ 40 ms.pop(); 41 } 42 else 43 cout<<ms.getMin()<<endl; 44 } 45 return 0; 46 }
最小栈问题,众所周知系列,就是用另一个min栈来存放当前栈中的最小元素。问题不大