๐Ÿ”’Algorithm

๋ฐฑ์ค€[JS] > 18111๋ฒˆ ๋งˆ์ธํฌ๋ž˜ํ”„ํŠธ

devWarrior 2025. 1. 26. 16:56

๋ฌธ์ œ๋งํฌ

https://www.acmicpc.net/problem/18111

๋ฌธ์ œํ’€์ด

๋ฌธ์ œ๋ฅผ ํ‘ธ๋ฉด์„œ ์•„๋ž˜์™€ ๊ฐ™์ด ๋ช‡ ๊ฐ€์ง€ ์œ ์˜ํ•  ์ ๋งŒ ์ฃผ์‹œํ•˜๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋‹ค.  

- ์ตœ์ข… ๋•…์˜ ๋†’์ด๋Š” 256์„ ์ดˆ๊ณผ ํ•  ์ˆ˜ ์—†๋‹ค.

- ์ตœ์†Œ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋Š” ๋•…์˜ ๋†’์ด๊ฐ€ ์—ฌ๋Ÿฌ๊ฐœ ์ผ ๊ฒฝ์šฐ ๊ฐ€์žฅ ๋†’์€ ๋•…์˜ ๋†’์ด๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

let fs = require("fs");
let input = fs.readFileSync("/dev/stdin").toString().trim().split("\n");

let [info, ...arr] = input;
let [N, M, B] = info.split(" ").map((n) => Number(n));
let set = [];
arr = arr.map((line) => {
    let lineArr = line.split(" ").map((n) => Number(n));

    lineArr.forEach((v) => {
        if (!set.includes(v)) {
            set.push(v);
        }
    });

    return lineArr;
});

let [minH, maxH] = [Math.min(...set), Math.max(...set)];
let spendTime = Infinity;
let proper_height = undefined;

for (let h = minH; h <= maxH; ++h) {
    if (h > 256) {
        break;
    }

    let block = B;
    let time = 0;
    for (let r = 0; r < N; ++r) {
        for (let c = 0; c < M; ++c) {
            let height = arr[r][c];
            if (height !== h) {
                if (height > h) {
                    block += height - h;
                    time += 2 * (height - h);
                } else {
                    block -= h - height;
                    time += h - height;
                }
            }
        }
    }

    if (block >= 0 && time <= spendTime) {
        spendTime = time;
        proper_height = h;
    }
}

console.log(spendTime + " " + proper_height);