kakasoo

[node.js] 패션왕 신해빈 ( 백준 9375번 ) 본문

프로그래밍/알고리즘 풀이

[node.js] 패션왕 신해빈 ( 백준 9375번 )

카카수(kakasoo) 2021. 4. 2. 09:51
반응형
const readline = require("readline");

rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

let cnt = 0;
let count = 0;
let clothes = 0;
input = [];
rl.on("line", (line) => {
    if (!count) {
        count = Number(line);
    } else {
        if (!isNaN(line - 0)) {
            clothes = Number(line);
            cnt++;
            if (clothes === 0) {
                console.log(0);
            }
        } else {
            input.push(line);
            if (input.length === clothes) {
                main();
                input = [];

                if (cnt === count) {
                    rl.close();
                }
            }
        }
    }
});

const main = () => {
    const clothes = [];

    input.forEach((cloth) => {
        const [name, kind] = cloth.split(" ");
        if (!clothes[kind]) {
            clothes[kind] = [];
        }
        clothes[kind].push(name);
    });

    let sum = 1;
    for (const kind in clothes) {
        sum *= clothes[kind].length + 1;
    }
    console.log(sum - 1);
};

그렇게 어려운 문제는 아닌데, 옷의 종류가 3가지 이상이라는 것을 못봤었다. 그래서 하드코딩한 게 틀렸었다.
clothes의 kind로 뭐가 올지 모르기 때문에 for문으로 해결해주었다.
그리고, 옷이 아예 없는 경우에도 문제가 나왔다.
모든 옷은 있는 경우 없는 경우가 있을 수 있기 때문에 가짓수에 +1을 하고 그것들의 곱으로 조합을 만들 수 있다.
그런데 아예 벗는 건 안되므로 최종적으로 -1을 해주어야 한다.
만약 옷이 아예 없는 경우면, 입을 수 있는 경우의 수가 -1이 나온다.
따라서 0인 경우를 따로 처리해주어야 했다.

반응형