Notice
Recent Posts
Recent Comments
Link
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Lennon FE

[๋ฐฑ์ค€ 1744๋ฒˆ] ์ˆ˜ ๋ฌถ๊ธฐ - ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(nodejs) ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm/Baekjoon

[๋ฐฑ์ค€ 1744๋ฒˆ] ์ˆ˜ ๋ฌถ๊ธฐ - ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(nodejs)

Lennon 2022. 2. 18. 21:25
728x90
๋ฐ˜์‘ํ˜•

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

 

1744๋ฒˆ: ์ˆ˜ ๋ฌถ๊ธฐ

๊ธธ์ด๊ฐ€ N์ธ ์ˆ˜์—ด์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๊ทธ ์ˆ˜์—ด์˜ ํ•ฉ์„ ๊ตฌํ•˜๋ ค๊ณ  ํ•œ๋‹ค. ํ•˜์ง€๋งŒ, ๊ทธ๋ƒฅ ๊ทธ ์ˆ˜์—ด์˜ ํ•ฉ์„ ๋ชจ๋‘ ๋”ํ•ด์„œ ๊ตฌํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ์ˆ˜์—ด์˜ ๋‘ ์ˆ˜๋ฅผ ๋ฌถ์œผ๋ ค๊ณ  ํ•œ๋‹ค. ์–ด๋–ค ์ˆ˜๋ฅผ ๋ฌถ์œผ๋ ค๊ณ  ํ•  ๋•Œ, ์œ„์น˜์—

www.acmicpc.net

const fs = require('fs');
const [n, ...input] = fs.readFileSync('../input.txt').toString().trim().split('\n').map(Number);

const negative = [];
const positive = [];
let zero = 0;
let answer = 0;

input.forEach((v) => {
  if (v < 0) {
    negative.push(v);
  } else if (v > 1) {
    positive.push(v);
  } else if (v === 0) {
    zero++;
  } else {
    answer++;
  }
});

negative.sort((a, b) => b - a);
positive.sort((a, b) => a - b);

while (positive.length) {
  if (positive.length === 1) {
    answer += positive.pop();
    break;
  }
  const value = positive.pop();
  const value2 = positive.pop();
  answer += value * value2;

  if (positive.length === 1) {
    answer += positive.pop();
    break;
  }
}

while (negative.length) {
  if (negative.length === 1) {
    if (zero !== 0) {
      zero--;
      break;
    } else {
      answer += negative.pop();
      break;
    }
  }
  if (negative.length % 2 === 1 && zero !== 0) {
    negative.shift();
    zero--;
  }
  const value = negative.pop();
  const value2 = negative.pop();
  answer += value * value2;

  if (negative.length === 1) {
    answer += negative.pop();
    break;
  }
}

console.log(answer);

1์€ ์–‘์ˆ˜์— ๊ณฑํ•˜๋ฉด ๋”ํ•˜๋Š” ๊ฐ’์ด ์ž‘์•„์ง€๋ฏ€๋กœ ex) 1, 11 => ๊ณฑํ•˜๋ฉด 11 or ๋”ํ•˜๋ฉด 12 ๊ทธ๋ƒฅ answer์— 1์„ ๋”ํ•ด์ค€๋‹ค.

์Œ์ˆ˜ ์–‘์ˆ˜๋ฅผ ๋”ฐ๋กœ ๋ฐฐ์—ด์— ์ €์žฅํ•ด sort๋กœ ์ •๋ ฌํ•œ ํ›„ ํ™€์ˆ˜, ์ง์ˆ˜ ๊ฐœ์ˆ˜๋ฅผ ์ƒ๊ฐํ•˜๋ฉฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ตฌ์„ฑํ•œ๋‹ค.

 

๋งŒ์•ฝ 0์ด ์žˆ์„ ๋•Œ๋Š” ์Œ์ˆ˜๊ฐ€ ํ™€์ˆ˜์ผ ๋•Œ ์Œ์ˆ˜์ค‘์— ๊ฐ€์žฅ ํฐ ๊ฐ’์ด๋ž‘ ๊ณฑํ•ด์ค˜์•ผ ํ•ฉ์ด ์ตœ๋Œ€์ด๋‹ค.

๊ทธ๋ฆฌ๊ณ , ์Œ์ˆ˜, ์–‘์ˆ˜๊ฐ€ 1๊ฐœ์”ฉ๋งŒ ์žˆ์„ ๋•Œ๋ฅผ ์ƒ๊ฐํ•ด ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ตฌ์ƒํ•˜๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
Comments