Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

코드와이

[BAEKJOON] 2493. 탑 본문

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);
	}
}

'acmicpc' 카테고리의 다른 글

[BAEKJOON] 9252. LCS2  (0) 2021.06.30
[BAEKJOON] 9019. DSLR  (0) 2021.06.28
[BAEKJOON] 1915. 가장 큰 정사각형  (0) 2021.06.25
[BAKEJOON] 2589. 보물섬  (0) 2021.06.24
[BAEKJOON] 17144. 미세먼지 안녕!  (0) 2021.06.22