Stack - 백준2493 탑

이형석·2024년 1월 26일

알고리즘 Phase1

목록 보기
6/59

이 문제는 다음과 같이 stack을 이용하면 뒤 탑들의 신호를 수신하는 탑을 관리할 수 있다.
1. stack이 비어있다. -> 신호를 받는 탑이 없다.
2. stack의 top의 탑이 송신한 탑보다 크다 -> top의 탑이 수신한다.
3. stack의 top의 탑이 송신한 탑보다 작다 -> 송신한 탑보다 큰 탑이 나올 때 까지 pop()한다.
4. 1 or 2 or 3 실행후 현재 탑을 stack에 push()한다.

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int topN = Integer.parseInt(br.readLine());
        Stack<int[]> stack = new Stack<>();
        StringBuilder sb = new StringBuilder();

        StringTokenizer st = new StringTokenizer(br.readLine());

        for (int i = 0; i < topN; i++) {
            //topInfo[0] _탑의 index, topInfo[1] _탑의 height
            int[] topInfo = new int[2];
            topInfo[0] = i+1;
            topInfo[1] = Integer.parseInt(st.nextToken());

            if (stack.isEmpty()) {
                sb.append("0 ");
            }else {
                while (true) {
                    if (stack.isEmpty()) {
                        sb.append("0 ");
                        break;
                    }
                    int[] receiver = stack.peek();
                    if (receiver[1] > topInfo[1]) {
                        sb.append(receiver[0] + " ");
                        break;
                    } else {
                        stack.pop();
                    }
                }
            }
            stack.push(topInfo);
        }
        System.out.println(sb);
    }
  • 스택에 integer배열 넣기
    Stack<int[]> stack = new Stack<>();
profile
금융IT 개발자

0개의 댓글