카테고리 없음

백준 Java | BOJ #1062 가르침

토마토. 2023. 1. 30. 16:33
package P1062;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class P1062 {
    static boolean[] visited;
    static ArrayList<String> words;
    static int selectedCount;
    static int n;
    static int k;
    static int max;
    public static void main(String[] args) throws FileNotFoundException {
        //System.setIn(new FileInputStream("src/P1062/input.txt"));
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        k = scanner.nextInt();
        words = new ArrayList<>();
        scanner.nextLine();
        for (int i=0;i<n;i++){
            String word = scanner.nextLine();
            words.add(word.replaceAll("[antic]", ""));
        }
        selectedCount = 5;
        if (k < 5){
            System.out.println(0);
            return;
        }
        if (k == 5){
            int count = 0;
            for (String word: words){
                if (word.equals("")){
                    count++;
                }
            }
            System.out.println(count);
            return;
        }
        if (k >= 26){
            System.out.println(n);
            return;
        }
        max = 0;

        visited = new boolean[26];
        visited[('a'-'a')] = true;
        visited[('n'-'a')] = true;
        visited[('t'-'a')] = true;
        visited[('i'-'a')] = true;
        visited[('c'-'a')] = true;

        for (int i=0;i<26;i++){
            if (visited[i] == false){
                dfs(i);
            }
        }
        System.out.println(max);
    }
    static void dfs(int index){
        // 1. 체크인 -> visited, selectedCount
        visited[index] = true;
        selectedCount++;
        // 2. 목적지인가 -> k == selectedCount -> 읽을 수 있는 단어 계산
        if (selectedCount == k){
            int count = count_read();
            max = Math.max(count, max);
        } else {
            // 3. 연결된 곳을 순회 a ~ z (current 보다 큰 곳만 갈 것)
            for (int i=index+1; i<26; i++){
                // 4. 갈 수 있는가 -> visited
                if (!visited[i]){
                    // 5. 간다 -> dfs
                    dfs(i);
                }
            }
        }
        // 6. 체크아웃 -> visited, selectedCount
        visited[index] = false;
        selectedCount--;
    }
    static int count_read(){
        int count = 0;
        for (int i=0;i<n;i++){
            boolean can_read = true;
            String word = words.get(i);
            for (int j=0;j<word.length();j++){
                if (!visited[word.charAt(j) - 'a']){
                    can_read = false;
                    break;
                }
            }
            if (can_read){
                count++;
            }
        }
        return count;
    }
}