[Algorithm Basics 20-Monotonic Stack]

Algorithm principle:
Use a monotonically increasing stack. When the element can be pushed onto the stack, the top element of the stack is the first element on the left that is smaller than it.
Take: 3 4 2 7 5 as an example, the process is as follows:
dynamic simulation process
insert image description here

Title:
Given a sequence of integers of length N, output the first number on the left of each number that is smaller than it, and output −1 if it does not exist.
input format

The first line contains the integer N, which represents the length of the sequence.

The second line contains N integers, representing the sequence of integers.
output format

A total of one line, containing N
integers, where the i-th number represents the first number on the left of the i-th number that is smaller than it, and if it does not exist, output −1.
data range

1≤N≤105

1≤ elements in the sequence ≤ 109

Input sample:

5
3 4 2 7 5

Sample output:
1
-1 3 -1 2 2

#include<iostream>
using namespace std;
const int maxn = 100010;
int stk[maxn],tt;

int main(){
    
    
    int N,k;
    cin>>N;
    while(N --){
    
    
        cin>>k;
        while(tt && stk[tt] >= k) tt--;
        if(!tt) cout<<"-1 ";
        else cout<<stk[tt]<<" ";
        stk[++ tt] = k;
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_60498436/article/details/132263037