총 10분 중 11분
2001
시즌 2개, 그리고 영화
시즌 2: 5화 “아일랜드”
출연: 이나영, 김민준, 김민정, 현빈
장르: 애초에 역경을 딛고 이룩하는 숭고한 사랑이란 없다. 그 역경 자체가 사랑이다.
프로그램 특징: 그 곳에서 살아남는 사랑이 어떤 모습으로 걸어오는지 기다려 보고 싶다.
Algorithm/Search [BOJ 10552][JAVA] 박싱/언박싱
728x90
반응형

[Silver II] DOM - 10552

문제 링크

성능 요약 메모리: 178132 KB, 시간: 1000 ms

분류 너비 우선 탐색, 깊이 우선 탐색, 그래프 이론, 그래프 탐색

제출 일자 2025년 4월 15일 12:16:15

문제 설명

In a retirement home, N senior citizens are watching television. The television programme consists of M channels denoted with numbers from 1 to M. Each of the pensioners has their own favourite and hated TV channel.

If the television is currently displaying the hated channel of a certain pensioner, he will get up, slowly walk over to the TV set and change the channel to his favourite and get back to his comfortable chair. If there are multiple pensioners who hate the current channel, the youngest of them will get up (he’s young, he doesn’t mind) and the rest will remain seated.

Of course, after one change of channel, it is possible that another pensioner finds the new channel intolerable so he will change that channel. Given the fact that the pensioners are stubborn, this may continue indefinitely.

For the pensioners’ favourite and hated channels and the initial channel on TV, determine the number of channel changes it takes for the pensioners to remain happy and seated.

입력

The first line of input contains three integers N, M and P (1 ≤ N, M ≤ 105, 1 ≤ P ≤ M), the number of pensioners, the number of TV channels and the initial channel displayed on TV.

Each of the following N lines contains two integers ai and bi (1 ≤ ai, bi ≤ M, ai ≠ bi), the favourite and hated channel of each pensioner.

The ordering of pensioners in the input is from the youngest to the oldest.

출력

The first and only line of output must contain the required number of channel changes. If the changes continue indefinitely, output -1.


코드

import java.util.*;

public class Main {
    static class Pair {
        int fav, hate ;

        public Pair(int a, int b) {
            this.fav = a;
            this.hate = b;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int programmes = sc.nextInt();
        int cur_ch = sc.nextInt();

        Pair[] pensioners = new Pair[n+1];
        List<Queue<Integer>> hateMap = new ArrayList<>(programmes+1);
        for (int i = 0; i <= programmes; i++) { //0부터???인이유가 뭐지
            hateMap.add(new LinkedList<>());
        }

        for (int i = 0; i < n; i++) {
            int fav = sc.nextInt();
            int hate = sc.nextInt();
            pensioners[i+1] = new Pair(fav, hate);
            hateMap.get(hate).add(i+1);
        }

        int result = 0;
        boolean[] visited = new boolean[programmes+1];

        while(true) {

            if (visited[cur_ch]) {
                System.out.println(-1); // 무한 루프 방지
                return;
            }

            visited[cur_ch] = true;

            Integer person = hateMap.get(cur_ch).poll();
            if (person!= null){
                cur_ch = pensioners[person].fav;
                result ++;                
            } else {
                System.out.println(result);
                return;
            }
        }
    }
}

 

person 값이 Null 인지 확인할 때 int person 은 컴파일 에러가 나고 Integer person은 통과되었다.

 

int ↔ Integer Auto-boxing / Unboxing

Integer은 객체고, int는 숫자 자료형이라 차이가 있다. 

int a = 10;
Integer obj = a;  // 박싱: int → Integer

int b = obj;      // 언박싱: Integer → int

 

자바 내부에서 이런식으로 처리한다.

Integer obj = Integer.valueOf(a);   // 박싱
int b = obj.intValue();             // 언박싱

 

List, Map 등의 컬렉션은 Integer의 객체형만 받을 수 있기 때문에 null 값 체크할 때 int 대신 Integer 로 변경해줘야한다. 

List<Integer> list = new ArrayList<>();
list.add(3);  // int → Integer 자동 변환 (오토 박싱)

Integer a = null;
int b = a;  // ❌ NullPointerException (언박싱 실패)

 

728x90
Algorithm/Search [BOJ 10552][JAVA] 박싱/언박싱