• Home
  • About
    • Develop2r photo

      Develop2r

      안녕하세요 IT 개발자 임기남입니다. 한걸음 한걸음 나아가는 개발자를 꿈꾸고 있습니다.

    • Learn More
    • Twitter
    • Facebook
    • Instagram
    • Github
    • Steam
  • Posts
    • All Posts
    • All Tags
  • Projects
  • Algorithm

백준 2493 탑

27 Jul 2020

Reading time ~1 minute

문제

백준 2493

KeyPoint

  • Stack 자료구조 이용
  • Index와 값을 묶어 객체로 사용하여 스택의 자료형으로 사용
  • 왼쪽으로 레이저를 송신하기 때문에 입력값의 거꾸로 실행

Code Snippets


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

public class S_2493 {
	
	static class A{
		int v,i;

		public A(int v, int i) {
			super();
			this.v = v;
			this.i = i;
		}
		
	}
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(br.readLine());
		StringTokenizer stk = new StringTokenizer(br.readLine());
		int[] arr = new int[N];
		int[] rs = new int[N];
		
		for (int i = 0; i < N; i++) {
			arr[i] = Integer.parseInt(stk.nextToken());
		}
		
		Stack<A> stack = new Stack<>();
		stack.add(new A(arr[N-1],N-1));
		
		
		for (int i = N-2; i >= 0; i--) {
			while(!stack.isEmpty()) {
				A tmp = stack.peek();
				if(arr[i]>tmp.v) {
					rs[tmp.i]=i+1;
					stack.pop();
				}else {
					stack.add(new A(arr[i],i));
					break;
				}
			}
			stack.add(new A(arr[i],i));
		}
		
		for (int i = 0; i < rs.length; i++) {
			System.out.print(rs[i]+" ");
		}
		
	}

}

comments

스택 자료구조를 사용하여 문제풀이를 진행하며 약간의 아이디어가 필요했다.
최적화를 위해 util에서 제공하는 Stack 이 아니라 직접 배열을 이용하여 stack 구조를 만들면 실행시간이 단축된다.



algorithmstackbaekjoon Share Tweet +1