가르침_1062

박상민·2024년 6월 20일
0

백준

목록 보기
31/36
post-thumbnail

문제

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

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

입력

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

출력

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

예제 입력 1

3 6
antarctica
antahellotica
antacartica

예제 출력 1

2

문제 분석

  • 단어를 읽으려면 최소 a, n, t, i, c 다섯 개의 알파벳을 알아야 함
  • 추가로 선택할 수 있는 알파벳의 개수는 K - 5개
  • 선택한 알파벳 조합으로 최대한 많은 단어를 읽을 수 있도록 한다.

입력 처리 및 초기 설정

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "input.txt";
const input = fs.readFileSync(filePath).toString().trim().split("\n");

const [N, K] = input[0].split(" ").map(Number);

첫 번째 줄에서 N (단어의 수)와 K (알파벳의 수)를 가져온다.

함수 초기 설정

function sol(n, k) {
    let uniqueList = []; // 각 단어에서 기본 알파벳을 제외한 고유 알파벳의 집합리스트
    let uniqueSet = new Set(); // 모든 단어에서 고유 알파벳을 모은 집합입니다.
    let cnt = 0; // 기본 알파벳만으로 읽을 수 있는 단어의 수를 세기 위한 변수

단어 분석

for (let i = 1; i <= n; i++) {
    let now = input[i].trim(); 
    let nowSet = new Set(now); // Set은 중복된 문자를 자동으로 제거
    let nowCnt = nowSet.size; //  현재 단어에서 고유한 문자의 수를 계산
  
    if (nowCnt > k) { // 고유한 문자의 수가 k보다 많으면, 해당 단어는 읽을 수 없다.
        continue;
    }

    if (nowCnt === 5) { // 고유한 문자의 수가 정확히 5개이면, antic로만 구성된 단어이므로 읽을 수 있다. 1 증가시키고 다음 단어로 넘어감.
      	cnt += 1;
        continue;
    }
	// 고유 알파벳 추출 및 저장
    let nowUnique = new Set([...nowSet].filter(x => !['a', 'n', 't', 'i', 'c'].includes(x)));
    uniqueList.push(nowUnique);
    uniqueSet = new Set([...uniqueSet, ...nowUnique]);
}
  • 각 단어를 읽고 고유 알파벳의 집합을 만든다.
  • 기본 알파벳(a, n, t, i, c)을 제외한 고유 알파벳만을 추출하여 uniqueList에 추가
  • uniqueSet에는 모든 단어에서 고유 알파벳을 모아 저장

읽을 수 있는 단어 수 계산

if (k < 5) {
    return 0;
}

if (uniqueList.length === 0) {
    return cnt;
}

if (uniqueSet.size <= k - 5) {
    return cnt + uniqueList.length;
}
  • K가 5보다 작으면 기본 알파벳조차 다 배울 수 없으므로 읽을 수 있는 단어가 없다.
  • uniqueList가 비어 있으면 모든 단어가 기본 알파벳만으로 구성되어 있어, 기본 알파벳만으로 읽을 수 있는 단어의 수를 반환
  • 고유 알파벳의 수가 K-5보다 작거나 같으면, 모든 단어를 읽을 수 있다.

최적의 알파벳 조합 찾기 (Brute-Force)

let maxCnt = 0;
let uniqueArray = Array.from(uniqueSet);

// 주어진 배열에서 selectNumber 개의 요소를 선택하는 모든 조합을 반환
function getCombinations(arr, selectNumber) {
    const results = [];
    if (selectNumber === 1) return arr.map((value) => [value]);
    arr.forEach((fixed, index, origin) => {
        const rest = origin.slice(index + 1);
        const combinations = getCombinations(rest, selectNumber - 1);
        const attached = combinations.map((combination) => [fixed, ...combination]);
        results.push(...attached);
    });
    return results;
}

// uniqueArray에서 K-5 개의 알파벳 조합을 생성
const combinations = getCombinations(uniqueArray, k - 5);

for (let caseSet of combinations) {
    let caseCnt = 0;
    let caseSetSet = new Set(caseSet);
    for (let candidateSet of uniqueList) {
        if ([...candidateSet].every(x => caseSetSet.has(x))) {
            caseCnt += 1;
        }
    }
    maxCnt = Math.max(maxCnt, caseCnt);
}
  • getCombinations 함수는 주어진 배열에서 selectNumber개의 요소를 선택하는 모든 조합을 반환
  • uniqueArray에서 K-5 개의 알파벳 조합을 생성
  • 각 조합마다 읽을 수 있는 단어의 수를 계산하여 최대값을 찾음

최종 결과 반환

  • cnt에 최대값 maxCnt
  • 기본 알파벳만으로 읽을 수 있는 단어 수 cnt에 최대값 maxCnt를 더하여 반환
cnt += maxCnt;
return cnt;
}
console.log(sol(N, K));

전체코드

const fs = require("fs");

const filePath = process.platform === "linux" ? "/dev/stdin" : "input.txt";
const input = fs.readFileSync(filePath).toString().trim().split("\n");

const [N, K] = input[0].split(" ").map(Number);

function sol(n, k) {
    let uniqueList = [];
    let uniqueSet = new Set();
    let cnt = 0;

    for (let i = 1; i <= n; i++) {
        let now = input[i].trim();
        let nowSet = new Set(now);
        let nowCnt = nowSet.size;

        if (nowCnt > k) {
            continue;
        }

        if (nowCnt === 5) {
            cnt += 1;
            continue;
        }

        let nowUnique = new Set([...nowSet].filter(x => !['a', 'n', 't', 'i', 'c'].includes(x)));
        uniqueList.push(nowUnique);
        uniqueSet = new Set([...uniqueSet, ...nowUnique]);
    }

    if (k < 5) {
        return 0;
    }

    if (uniqueList.length === 0) {
        return cnt;
    }

    if (uniqueSet.size <= k - 5) {
        return cnt + uniqueList.length;
    }

    let maxCnt = 0;
    let uniqueArray = Array.from(uniqueSet);

    function getCombinations(arr, selectNumber) {
        const results = [];
        if (selectNumber === 1) return arr.map((value) => [value]);
        arr.forEach((fixed, index, origin) => {
            const rest = origin.slice(index + 1);
            const combinations = getCombinations(rest, selectNumber - 1);
            const attached = combinations.map((combination) => [fixed, ...combination]);
            results.push(...attached);
        });
        return results;
    }

    const combinations = getCombinations(uniqueArray, k - 5);

    for (let caseSet of combinations) {
        let caseCnt = 0;
        let caseSetSet = new Set(caseSet);
        for (let candidateSet of uniqueList) {
            if ([...candidateSet].every(x => caseSetSet.has(x))) {
                caseCnt += 1;
            }
        }
        maxCnt = Math.max(maxCnt, caseCnt);
    }

    cnt += maxCnt;
    return cnt;
}

console.log(sol(N, K));
profile
I want to become a UX Developer

0개의 댓글