Developing Myself Everyday
article thumbnail
 

1062번: 가르침

첫째 줄에 단어의 개수 N과 K가 주어진다. N은 50보다 작거나 같은 자연수이고, K는 26보다 작거나 같은 자연수 또는 0이다. 둘째 줄부터 N개의 줄에 남극 언어의 단어가 주어진다. 단어는 영어 소문

www.acmicpc.net

문제

남극에 사는 김지민 선생님은 학생들이 되도록이면 많은 단어를 읽을 수 있도록 하려고 한다. 그러나 지구온난화로 인해 얼음이 녹아서 곧 학교가 무너지기 때문에, 김지민은 K개의 글자를 가르칠 시간 밖에 없다. 김지민이 가르치고 난 후에는, 학생들은 그 K개의 글자로만 이루어진 단어만을 읽을 수 있다. 김지민은 어떤 K개의 글자를 가르쳐야 학생들이 읽을 수 있는 단어의 개수가 최대가 되는지 고민에 빠졌다.

남극언어의 모든 단어는 "anta"로 시작되고, "tica"로 끝난다. 남극언어에 단어는 N개 밖에 없다고 가정한다. 학생들이 읽을 수 있는 단어의 최댓값을 구하는 프로그램을 작성하시오.

입력

첫째 줄에 단어의 개수 N과 K가 주어진다. N은 50보다 작거나 같은 자연수이고, K는 26보다 작거나 같은 자연수 또는 0이다. 둘째 줄부터 N개의 줄에 남극 언어의 단어가 주어진다. 단어는 영어 소문자로만 이루어져 있고, 길이가 8보다 크거나 같고, 15보다 작거나 같다. 모든 단어는 중복되지 않는다.

출력

첫째 줄에 김지민이 K개의 글자를 가르칠 때, 학생들이 읽을 수 있는 단어 개수의 최댓값을 출력한다.


 

나의 풀이

이 문제는 26개의 알파벳 중에서 k개를 골라야 하기 때문에 조합을 사용해야 합니다. 26개의 알파벳 중 5개의 알파벳은 기본적으로 주어지기 때문에 해당하는 알파벳은 제외하고 k - 5개의 알파벳을 선택해야 합니다.

 

그러므로 k - 5보다 작은 숫자를 선택해야 하는 경우에는 읽을 수 있는 단어가 없게 됩니다.

 

조합을 사용해 알파벳을 선택하고 알파벳의 선택을 완료했다면 읽을 수 있는 단어를 세면 됩니다.

 

Kotlin

import kotlin.math.max

lateinit var words: Array<String>
val visited = BooleanArray(26)
val origin = arrayOf('a' - 'a', 'n' - 'a', 't' - 'a', 'i' - 'a', 'c' - 'a')

fun main() = with(System.`in`.bufferedReader()) {

    val (n, k) = readLine().split(" ").map { it.toInt() }

    words = Array(n) { readLine().removePrefix("anta").removeSuffix("tica") }

    origin.forEach {
        visited[it] = true
    }

    combination(0, k - 5)

    println(answer)
}

var answer = 0

fun combination(start: Int, target: Int) {
    if (target < 0) return

    if (target == 0) {
        answer = max(answer, countWords())
        return
    }

    for (i in start until 26) {
        if (origin.contains(i)) continue

        visited[i] = true
        combination(i + 1, target - 1)
        visited[i] = false
    }
}

fun countWords(): Int {
    var cnt = 0
    for (word in words) {
        var check = true

        for (c in word) {
            if (!visited[c - 'a']) {
                check = false
                break
            }
        }

        if (check) cnt++
    }

    return cnt
}

 

Java

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

public class Main {

    static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer st;

    static int answer;
    static List<String> words = new ArrayList<>();
    static boolean[] visited = new boolean[26];
    static List<Integer> origin = Arrays.asList('a' - 'a', 'n' - 'a', 't' - 'a', 'i' - 'a', 'c' - 'a');

    public static void main(String[] args) throws IOException {
        st = new StringTokenizer(bf.readLine());
        int n = Integer.parseInt(st.nextToken());
        int k = Integer.parseInt(st.nextToken());

        for (int i = 0; i < n; i++) {
            String word = bf.readLine().replace("anta", "").replace("tica", "");
            words.add(word);
        }

        for (int i : origin) {
            visited[i] = true;
        }

        combination(0, k - 5);

        System.out.println(answer);
    }

    static void combination(int start, int target) {
        if (target < 0) return;

        if (target == 0) {
            answer = Math.max(answer, countWords());
            return;
        }

        for (int i = start; i < 26; i++) {
            if (origin.contains(i)) continue;

            visited[i] = true;
            combination(i + 1, target - 1);
            visited[i] = false;
        }
    }

    static int countWords() {
        int cnt = 0;
        for (String word : words) {
            boolean check = true;

            for (char c : word.toCharArray()) {
                if (!visited[c - 'a']) {
                    check = false;
                    break;
                }
            }

            if (check) cnt++;
        }

        return cnt;
    }
}

 

 

profile

Developing Myself Everyday

@배준형

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!