๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์ฝ”๋”ฉํ…Œ์ŠคํŠธ/TIL

[99ํด๋Ÿฝ] 20์ผ์ฐจ ๋ฌธ์ œ: ํšŒ์ „์ดˆ๋ฐฅ

by moon101 2025. 2. 15.

 

 

๋ฐฑ์ค€ ํšŒ์ „์ดˆ๋ฐฅ ๋ฌธ์ œ. ์ด์ œ ๋ฌธ์ œ์˜ ๋‹ต์ด ๊ธธ์–ด์ง€๊ณ  ๋ณต์žกํ•ด์ง€๋ฉด์„œ gpt์— ์˜์กดํ•˜๊ณ  ์žˆ๋‹ค....

ํ•ด์‹œ๋งต์˜ putIfAbsent() ๋ฉ”์†Œ๋“œ๋Š” ์ž˜ ์‚ฌ์šฉํ•ด ๋ณด์ง€ ์•Š์•˜๋Š”๋ฐ ๋‹ค์Œ๊ธฐํšŒ์— ์‚ฌ์šฉํ•ด๋ณด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค. 

 

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

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

        int N = Integer.parseInt(st.nextToken()); // ์†๋‹˜ ์ˆ˜
        int M = Integer.parseInt(st.nextToken()); // ์ดˆ๋ฐฅ ์ˆ˜

        // ์ดˆ๋ฐฅ์„ ์›ํ•˜๋Š” ์†๋‹˜ ๋ฆฌ์ŠคํŠธ
        Map<Integer, Queue<Integer>> sushiToCustomers = new HashMap<>();
        int[] sushiCount = new int[N]; // ์†๋‹˜๋ณ„๋กœ ๋จน์€ ์ดˆ๋ฐฅ ๊ฐœ์ˆ˜
        Set<Integer>[] customerOrders = new HashSet[N]; // ์†๋‹˜๋ณ„ ์ฃผ๋ฌธ ๋ชฉ๋ก

        // ์†๋‹˜๋“ค์˜ ์ฃผ๋ฌธ ๋ชฉ๋ก์„ ์ €์žฅ
        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            int k = Integer.parseInt(st.nextToken()); // ์ฃผ๋ฌธํ•œ ์ดˆ๋ฐฅ ๊ฐœ์ˆ˜
            customerOrders[i] = new HashSet<>();

            for (int j = 0; j < k; j++) {
                int sushiType = Integer.parseInt(st.nextToken());
                customerOrders[i].add(sushiType); // ์†๋‹˜์˜ ์ฃผ๋ฌธ ๋ชฉ๋ก์— ์ถ”๊ฐ€

                // ์ดˆ๋ฐฅ๋ณ„๋กœ ํ•ด๋‹น ์ดˆ๋ฐฅ์„ ์›ํ•˜๋Š” ์†๋‹˜์„ ํ์— ์ €์žฅ
                sushiToCustomers.putIfAbsent(sushiType, new LinkedList<>());
                sushiToCustomers.get(sushiType).add(i);
            }
        }

        // ์ดˆ๋ฐฅ์„ ๋งŒ๋“ค๋ฉด์„œ ์†๋‹˜์—๊ฒŒ ์ „๋‹ฌ
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < M; i++) {
            int sushi = Integer.parseInt(st.nextToken());

            // ์ดˆ๋ฐฅ์„ ์›ํ•˜๋Š” ์†๋‹˜์ด ์กด์žฌํ•˜๋ฉด
            if (sushiToCustomers.containsKey(sushi)) {
                Queue<Integer> queue = sushiToCustomers.get(sushi);

                while (!queue.isEmpty()) {
                    int customer = queue.poll(); // ์ดˆ๋ฐฅ์„ ์›ํ•˜๋Š” ์ฒซ ๋ฒˆ์งธ ์†๋‹˜ ์„ ํƒ

                    // ๋งŒ์•ฝ ์†๋‹˜์ด ์ด๋ฏธ ํ•ด๋‹น ์ดˆ๋ฐฅ์„ ๋จน์—ˆ๋‹ค๋ฉด ํŒจ์Šค
                    if (!customerOrders[customer].contains(sushi)) continue;

                    // ์†๋‹˜์ด ์ดˆ๋ฐฅ์„ ๋จน์Œ
                    sushiCount[customer]++;
                    customerOrders[customer].remove(sushi); // ํ•œ ๋ฒˆ ๋จน์—ˆ์œผ๋‹ˆ ์‚ญ์ œ
                    break; // ์ดˆ๋ฐฅ์„ ๋จน์—ˆ์œผ๋ฉด ์ข…๋ฃŒ (๋‹ค์Œ ์†๋‹˜์€ ๋ฐ›์„ ์ˆ˜ ์—†์Œ)
                }
            }
        }

        // ๊ฒฐ๊ณผ ์ถœ๋ ฅ
        StringBuilder sb = new StringBuilder();
        for (int count : sushiCount) {
            sb.append(count).append("\n");
        }
        System.out.print(sb);
    }
}
 

๋Œ“๊ธ€