Java
[백준 2493] 탑 (JAVA)
iheeeee6-6
2023. 5. 2. 21:02
728x90
https://www.acmicpc.net/problem/2493
2493번: 탑
첫째 줄에 탑의 수를 나타내는 정수 N이 주어진다. N은 1 이상 500,000 이하이다. 둘째 줄에는 N개의 탑들의 높이가 직선상에 놓인 순서대로 하나의 빈칸을 사이에 두고 주어진다. 탑들의 높이는 1
www.acmicpc.net
1. 들어오는 순서대로 스택에 값이 있다면 높이를 비교한다.
2. 스택에서 peek한 높이가 더 높을 경우에는 해당 값이 수신하는 건물이 된다.
3. 더 낮을 경우에는 이 건물의 영향을 받지 않을 것이기 때문에 pop한다!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
static class Node {
int height,index;
Node(int height,int index){
this.height=height;
this.index=index;
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Stack<Node> s = new Stack<>();
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 1; i <= n; i++) {
int h = Integer.parseInt(st.nextToken());
int result = 0;
while (!s.isEmpty()) {
Node temp = s.peek();
if (h < temp.height) {
result=temp.index;
break;
}else s.pop();
}
sb.append(result).append(" ");
s.add(new Node(h,i));
}
System.out.println(sb);
}
}