알고리즘공부(Algorithm Study)/문제풀이(ProblemSolving)

[큐] 백준 15828 Router

Chaany 2022. 12. 3.
728x90
package 큐덱;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class boj_15828_Router {
    private static Queue<Integer> router;
    public static void main(String[] args) throws IOException {
        router = new LinkedList<>();
        int routerSize, packetCount = 0;

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        routerSize = Integer.parseInt(br.readLine());
        int InputValue = -2;

        while(InputValue != -1){
            InputValue = Integer.parseInt(br.readLine());

            // -1 입력의 끝
            if(InputValue == -1) break;

            // 0 패킷 처리
            if(InputValue == 0){
                handlePacket();
                packetCount = packetCount == 0 ? 0 : packetCount - 1;
                continue;
            }

            // 패킷 적재 or 버리기
            if(packetCount == routerSize) continue;
            router.offer(InputValue);
            packetCount++;
        }

        StringBuilder sb = new StringBuilder();

        if(packetCount == 0) {
            sb.append("empty ");
        }

        while (!router.isEmpty()) {
            sb.append(router.poll() +" ");
        }
        sb.setLength(sb.length()-1);
        System.out.println(sb.toString());

    }

    private static void handlePacket() {
        if(!router.isEmpty()) router.poll();
    }
}

 

해당 문제는 큐를 이용한 문제로 라우터 작동 방식에 대한 배경지식을 조금이나마 습득할 수 있는 문제다.

 

오랜만에 큐와 스트링빌더를 활용해 풀었던 문제...!

728x90

댓글