1 #include<iostream> 2 #include<stack> 3 using namespace std; 4 class min_stack 5 { 6 public: 7 void push(int); 8 void pop(); 9 int min();10 int size()11 {12 return data.size();13 }14 private:15 stack<int> data;16 stack<int> min_data;17 };18 void min_stack::push(int value)19 {20 data.push(value);21 if (min_data.size()==0 || min_data.top() > value)22 { 23 min_data.push(value);24 }25 else26 {27 min_data.push(min_data.top());28 }29 }30 void min_stack::pop()31 {32 if (data.size()>0)33 {34 min_data.pop();35 data.pop();36 }37 }38 int min_stack::min()39 {40 return min_data.top();41 }42 43 int main(int argc, char **argv)44 {45 int n,m;46 char ci;47 while(cin>>n)48 {49 min_stack mystack;50 for (int i=0; i<n; i++)51 {52 cin>>ci;53 switch (ci)54 {55 case ‘s‘:56 cin>>m;57 mystack.push(m);58 cout<<mystack.min()<<endl;59 break;60 case ‘o‘:61 mystack.pop();62 if (mystack.size()==0)63 {64 cout<<"NULL"<<endl;65 }66 else67 {68 cout<<mystack.min()<<endl;69 }70 break;71 }72 } 73 }74 return 1;75 }76 /**************************************************************77 Problem: 152278 User: xuebintian79 Language: C++80 Result: Accepted81 Time:140 ms82 Memory:1524 kb83 ****************************************************************/
-
Description:
-
Define the data structure of the stack. Implement a min function in this type to obtain the minimum element of the stack.
-
Input:
-
The input may contain multiple test examples. The input ends with EOF.
For each test case, the first input behavior is an integer N (1 <=n <= 1000000), and N represents the number of steps to be entered.
Next there are n rows. Each row starts with a letter CI.
When CI ='s, there is a number K next, which means K is pushed into the stack.
When CI = 'O', the top element of the stack is displayed.
-
Output:
-
Corresponding to each operation in each test case,
If the stack is not empty, the minimum element in the corresponding stack is output. Otherwise, the output is null.