单调栈

59 阅读1分钟
  • 常见模型:找出每个数左边离它最近的比它大/小的数

模板

  • C++
int tt = 0;
for (int i = 1; i <= n; i ++ )
{
    while (tt && check(stk[tt], i)) tt -- ;
    stk[ ++ tt] = i;
}
  • Java
int tt = 0;
for (int i = 1; i <= n; i++) {
    while (tt != 0 && check(stk[tt], i)) {
        tt--;
    }
    stk[++tt] = i;
}

练习

01 单调栈

  • 题目

Snipaste_2023-03-01_22-49-34.png

  • 题解
import java.io.*;

public class Main {
    public static final int N = 100010;
    public static int n;
    public static int stk[] = new int[N];
    public static int tt = 0;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        n = Integer.parseInt(br.readLine());
        String[] str1 = br.readLine().split(" ");

        for (int i = 0; i < n; i++) {
            int x = Integer.parseInt(str1[i]);
            while (tt != 0 && stk[tt] >= x) {
                tt--;
            }
            if (tt != 0) {
                pw.print(stk[tt] + " ");
            } else {
                pw.print(-1 + " ");
            }
            stk[++tt] = x;
        }

        pw.close();
        br.close();
    }
}