끄적끄적 코딩
article thumbnail
Published 2023. 2. 13. 20:32
[Java] 백준 2493번 탑 알고리즘
728x90

각 탑들에서 레이저를 발사할 때 수신받는 탑의 위치를 출력하는 문제입니다.

탑은 왼쪽에 가장 가까이 있으면서 현재 위치 보다 높은 곳에서 받게됩니다.
맨 오른쪽부터 왼쪽 값을 비교하고 큰값인 경우 해당위치에서 수신하는 것이므로 저장을 하고 다음으로 넘어갑니다.
작을 경우 해당 값을 스택에 넣고 다음위치 탐색을 반복합니다.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Stack;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		int n = Integer.parseInt(br.readLine());
		int[] top = new int[n+1];
		int[] receive = new int[n+1];
		Stack<Pair> stack = new Stack<>();
		StringTokenizer st = new StringTokenizer(br.readLine());
		for(int i=1; i<=n; ++i) {
			top[i] = Integer.parseInt(st.nextToken());
		}
		
		for(int i=n; i>0; --i) {
			if(top[i] < top[i-1]) {
				receive[i] = i-1;
				while(!stack.isEmpty() && stack.peek().num < top[i-1]){
					receive[stack.peek().index] = i-1;
					stack.pop();
				}
				continue;
			}
			stack.push(new Pair(top[i], i));
		}
		
		for(int i=1; i<=n; ++i) {
			bw.write(receive[i] + " ");
		}
		bw.write("\n");
		bw.close();
	}
	public static class Pair {
		int num, index;
		public Pair(int num, int index) {
			this.num = num;
			this.index = index;
		}
	}
}

검색 태그