Skip to content

[20260211] BOJ / G1 / 카드 게임 / 김민진#1923

Merged
ShinHeeEul merged 1 commit intomainfrom
zinnnn37
Feb 11, 2026
Merged

[20260211] BOJ / G1 / 카드 게임 / 김민진#1923
ShinHeeEul merged 1 commit intomainfrom
zinnnn37

Conversation

@zinnnn37
Copy link
Contributor

🧷 문제 링크

카드 게임

🧭 풀이 시간

40분

👀 체감 난이도

✏️ 문제 설명

주어진 카드 중 철수가 내고자 하는 카드보다 더 큰 카드 내기
단, 이미 낸 카드는 사용할 수 없음

🔍 풀이 방법

upperbound + union-find

기본적으로 upperbound로 내야하는 카드보다 더 큰 카드를 찾는데 이미 낸 카드는 사용 불가능하니까 분리집합에 낼 수 있는 가장 작은 수를 저장함
카드를 내고난 후 union(x, x+1) 해서 저장

⏳ 회고

낼 수 있는 카드를 미리 저장해두면 이분탐색 없이 분리집합으로도 된다고 합니다

@ShinHeeEul ShinHeeEul merged commit 101c816 into main Feb 11, 2026
1 check passed
@zinnnn37
Copy link
Contributor Author

import java.io.*;
import java.util.StringTokenizer;

public class BJ_16566_카드_게임_union_find {

    private static final BufferedReader  br = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter  bw = new BufferedWriter(new OutputStreamWriter(System.out));
    private static final StringBuilder   sb = new StringBuilder();
    private static       StringTokenizer st;

    private static int N, M, K;
    private static int[] choices, parents;
    private static boolean[] cards;

    public static void main(String[] args) throws IOException {
        init();
        sol();
    }

    private static void init() throws IOException {
        st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        K = Integer.parseInt(st.nextToken());

        cards = new boolean[N + 1];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < M; i++) {
            cards[Integer.parseInt(st.nextToken())] = true;
        }

        parents = new int[N + 2];
        int parent = 0;
        for (int i = N; i > 0; i--) {
            if (cards[i]) parent = i;
            parents[i] = parent;
        }

        choices = new int[K];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < K; i++) {
            choices[i] = Integer.parseInt(st.nextToken());
        }
    }

    private static void sol() throws IOException {
        for (int choice : choices) {
            int target = find(choice + 1);

            sb.append(parents[target]).append("\n");
            union(target, target + 1);
        }
        bw.write(sb.toString());
        bw.flush();
        bw.close();
        br.close();
    }

    private static int find(int a) {
        if (parents[a] == a) {
            return a;
        }

        return parents[a] = find(parents[a]);
    }

    private static void union(int a, int b) {
        int rootA = find(a);
        int rootB = find(b);

        parents[rootA] = rootB;
    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants