2025년 01월 19일

2025. 1. 19 알고리즘 오답노트

알고리즘

1. 블랙잭 (백준 2798번)

링크
틀린 이유를 곱씹어 보자면.. break문이 아닌 continue를 써야 했었다. 진짜 허무하다..
더 큰 수가 있을 수 있는 데 break문으로 순회를 멈춰서 더 큰 수 순회를 멈춘 것 같다.

내 답안

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

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

let max = 0;

for (let i = 0; i < N; i++) {
    for (let j = i + 1; j < N; j++) {
        for (let k = j + 1; k < N; k++) {
            const sum = arr[i] + arr[j] + arr[k];
            if (sum > M) break;
            if (max < sum) max = sum;
        }
    }
}

console.log(max);

고친 답안

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

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

let max = 0;

for (let i = 0; i < N; i++) {
    for (let j = i + 1; j < N; j++) {
        for (let k = j + 1; k < N; k++) {
            const sum = arr[i] + arr[j] + arr[k];
            if (sum > M) continue; // 이 부분
            if (max < sum) max = sum;
        }
    }
}

console.log(max);

2. Hashing (백준 15829번)

링크
해싱 알고리즘을 구현하는 문제였다. 틀린 이유는 모듈러 연산에 대한 이해도 부족이었다.
질문 게시판을 둘러보다가 모듈러 연산의 곱셈법칙을 참고하래서, 다음과 같이 최대한 이해하려고 노력해봤다.
모듈러 연산 곱셈법칙

내 답안

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

const N = Number(input[0]);
const M = 1234567891;
const arr = input[1].split("");

const alphabets = [
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
];

let hash = 0;

for (let i = 0; i < N; i++) {
    const idx = alphabets.indexOf(arr[i]) + 1;
    hash += ((idx % M) * (31 ** i % M)) % M;
}

console.log(hash % M);

고친 답안

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

const N = Number(input[0]);
const M = 1234567891;
const str = input[1];

let hash = 0;
let r = 1;

for (let i = 0; i < N; i++) {
    hash += (str.charCodeAt(i) - 96) * r;
    hash %= M;
    r *= 31;
    r %= M;
}

console.log(hash);