acmicpc

[BAEKJOON] 2493. 탑

코드와이 2021. 6. 25. 11:26

 

stack

문제링크

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

 

2493번: 탑

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

www.acmicpc.net

 

자료구조 stack을 사용하면 쉽게 풀 수 있는 문제이다. 값과 그 index 값을 저장할 수 있는 class(Point)를 만들어서 StringBuilder에 추가시켜준다.

package acmicpc.Gold5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;

public class 탑 {

	static class Point{
		int x;
		int idx;
		public Point(int x, int idx) {
			super();
			this.x = x;
			this.idx = idx;
		}
	}
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		StringBuilder sb = new StringBuilder();
		
		int n = Integer.parseInt(br.readLine());
		Stack<Point> stack = new Stack<>();
		
		st = new StringTokenizer(br.readLine());
		int x = -1;
		for(int i = 0 ; i < n ; i++) {
			x = Integer.parseInt(st.nextToken());
			
			if(stack.isEmpty()) {
				sb.append(0).append(" ");
				stack.add(new Point(x, i));
			} else {
				while(!stack.isEmpty()) {

					Point s = stack.pop();
					if(s.x >= x) {
						stack.add(s);
						stack.add(new Point(x, i));
						sb.append(s.idx + 1).append(" ");
						break;
					}
				}
				
				if(stack.isEmpty()) {
					stack.add(new Point(x,i));
					sb.append(0).append(" ");
				}
			}
		}
		sb.setLength(sb.length()-1);
		System.out.println(sb);
	}
}