[Original] monotonous stack analysis template +

Monotone stack, by definition, is a set of data. Generating a monotonic increasing or decreasing the value of the stack the stack.

Monotonous stack significance:

In the process of generating a monotone stack can be recorded the number of i left within the current location of the array, larger or smaller than the first number of the number of location i (ie decreasing large, namely small increments) (starting from the left end Drawing under the circumstances, the right to start the stack is the number to the right)

Stack monotonically decreasing generation process:

1, in an array, a number of extraction;

2, if the stack is empty, directly into, and record the current position of the source array no minimum / maximum values;

3, if the stack is not empty, the top element in the array and comparing the extracted values;

4, if greater than the top element extraction elements in the array, the pop-top element, the top element of the new comparison continues until the top of the stack is smaller than the extracted elements in the array (Jump step 5) or an empty stack ( jump step 2);

5, if the top element is smaller than the extraction of elements in the array, the first record is the current top of the stack (see stack monotonous sense), after extracting elements onto the stack.

 

Codes are as follows:

 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 stack <int> stk;
 5 int main(){
 6     int n,list1[50],L[50];
 7     cin>>n;
 8     for(int i=0;i<n;i++) cin>>list1[i];
 9     for(int i=0;i<n;i++){
10         while(!stk.empty()&&list1[stk.top()]>=list1[i]){//Current stack is monotonically decreasing, to <= monotonically increasing 
. 11              stk.pop ();
 12 is          }
 13 is          IF (stk.empty ()) {
 14              L [I] = - . 1 ;
 15          }
 16          the else L [I] = stk.top ();
 . 17          stk.push (I);
 18 is      }
 . 19 }

 

Guess you like

Origin www.cnblogs.com/Never-Land/p/11291899.html
Recommended