BOJ_G5_2493
π [G5_2493] ν
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
Stack<Integer> rootStack = new Stack<>();
Stack<Integer> indexStack = new Stack<>();
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int first = Integer.parseInt(st.nextToken());
rootStack.push(first);
indexStack.push(1);
sb.append("0 ");
for(int i=2; i<=N; i++) {
int value = Integer.parseInt(st.nextToken());
while(!rootStack.isEmpty()) {
// stackμ μλ κ°μ΄ μλ‘ push λλ €λ κ°λ³΄λ€ ν΄ κ²½μ°
if(value < rootStack.peek()) {
sb.append(indexStack.peek() + " ");
break;
}
// stackμ μλ κ°μ΄ μλ‘ push λλ €λ κ°λ³΄λ€ μμ κ²½μ°
rootStack.pop();
indexStack.pop();
}
// stackμ΄ λΉμ΄μμ κ²½μ°
if(rootStack.isEmpty()) {
sb.append("0 ");
}
rootStack.push(value);
indexStack.push(i);
}
System.out.println(sb.toString());
}
}
π€ λμ μκ°
μ²μμ 2μ€ forλ¬ΈμΌλ‘ νμλλ° μμ Nμ΄ ν° νμΈμ§ μκ°, λ©λͺ¨λ¦¬ μ€λ₯κ° λ΄λ€.
κ·Έλμ λ°©λ²μ κ³ λ―Όνλ€κ° λμ ν μκ°μ΄ μλμ ꡬκΈλ§μ ν΅ν΄ STACKμ ν΅ν΄ νΈλ λ°©λ²μ μκ² λμλ€..
λ κ°μ STACKμ μ΄μ©ν΄ indexμ νμ λμ΄λ₯Ό pushνλ €λ κ°μ΄ λ ν°κ²½μ°, μμκ²½μ°, STACKμ΄ λΉ κ²½μ°λ₯Ό λλ μ νμ΄μ£Όμλ€.