Scroll indicator done
728x90

https://www.acmicpc.net/problem/16508

 

16508번: 전공책

곧 졸업을 앞둔 민호는 대학교 생활 동안 구매만 해놓고 한 번도 펴보지 않은 전공책에 먼지가 쌓여 있는 것을 보고는, 이 책들을 어떻게 처리해야 할지 고민 중이다. 열심히 고민한 끝에 민호는

www.acmicpc.net

 

 

코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Main {
    static ArrayList<Book> arrayList = new ArrayList<>();
    static String str;
    static int[] cnt = new int[26];
    static int[] select = new int[26];
    static int n, min = Integer.MAX_VALUE;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        str = br.readLine();
        n = Integer.parseInt(br.readLine());
        for (int i = 0; i < str.length(); i++) {
            cnt[str.charAt(i) - 'A']++;
        }

        for (int i = 0; i < n; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int price = Integer.parseInt(st.nextToken());
            String title = st.nextToken();
            arrayList.add(new Book(price, title));
        }

        dfs(0, 0);
        System.out.println(min == Integer.MAX_VALUE ? -1 : min);
    }

    public static void dfs(int len, int total) {
        if (len == n) {
            if (check()) {
                min = Math.min(total, min);
            }
            return;
        }

        // 현재 책을 선택할 때
        for (int i = 0; i < arrayList.get(len).title.length(); i++) {
            select[arrayList.get(len).title.charAt(i) - 'A']++;
        }
        dfs(len+1, total + arrayList.get(len).price);

        // 선택하지 않을 때
        for (int i = 0; i < arrayList.get(len).title.length(); i++) {
            select[arrayList.get(len).title.charAt(i) - 'A']--;
        }
        dfs(len + 1, total);
    }

    static boolean check() {
        for (int i = 0; i < 26; i++) {
            if(cnt[i] > select[i]) return false;
        }
        return true;
    }

    public static class Book {
        int price;
        String title;

        public Book(int price, String title) {
            this.price = price;
            this.title = title;
        }
    }

}

728x90

'BAEKJOON > Java' 카테고리의 다른 글

[B21278][호석이 두 마리 치킨][java]  (0) 2023.10.11
[B14501][퇴사][java]  (0) 2023.10.10
[B1503][비슷한 단어][java]  (0) 2023.10.10
[B1503][세 수 고르기][java]  (0) 2023.10.10
[B12919][A와 B 2][java]  (0) 2023.10.09