본문 바로가기
코딩테스트

[백준] 2493번 '탑' - Java

by CuckooBird 2023. 8. 11.

https://www.acmicpc.net/problem/2493

 

2493번: 탑

첫째 줄에 탑의 수를 나타내는 정수 N이 주어진다. N은 1 이상 500,000 이하이다. 둘째 줄에는 N개의 탑들의 높이가 직선상에 놓인 순서대로 하나의 빈칸을 사이에 두고 주어진다. 탑들의 높이는 1

www.acmicpc.net


문제


코드

import java.io.*;
import java.util.*;

class Top {
	int num;
	int height;
	
	Top(int num, int height){
		this.num = num;
		this.height = height;
	}
}

public class Main {
	private static final BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
	private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	
	public static void main(String[] args) throws IOException {
		int n = Integer.parseInt(bf.readLine());
		StringTokenizer st = new StringTokenizer(bf.readLine());
		
		int[] ans = new int[n];
		Stack<Top> tower = new Stack<>();
		for(int i = 1 ; i <= n ; i++) {
			int height = Integer.parseInt(st.nextToken());
			
			if(tower.isEmpty()) {
				ans[i - 1] = 0;
				tower.push(new Top(i, height));
			} else {
				while(true) {
					if(tower.isEmpty()) {
						ans[i - 1] = 0;
						tower.push(new Top(i, height));
						break;
					}
					
					Top top = tower.peek();
					if(top.height > height) {
						ans[i - 1] = top.num;
						tower.push(new Top(i, height));
						break;
					} else {
						tower.pop();
					}
				}
			}
		}
		
		for(int i = 0 ; i < n ; i++) {
			bw.write(ans[i] + " ");
		}
		
		bf.close();
		bw.flush();
		bw.close();
	}
}

반대로 생각하고 있었는데 시간 초과가 나더라구요.. 어렵..