๐Ÿ”ฅ Algorithm/Baekjoon

[๋ฐฑ์ค€ 1309๋ฒˆ] ๋™๋ฌผ์› - ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(nodejs)

Lennon 2022. 3. 18. 19:00
728x90
๋ฐ˜์‘ํ˜•

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

 

1309๋ฒˆ: ๋™๋ฌผ์›

์ฒซ์งธ ์ค„์— ์šฐ๋ฆฌ์˜ ํฌ๊ธฐ N(1≤N≤100,000)์ด ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

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

let input;

rl.on('line', function (line) {
  input = +line;
  rl.close();
}).on('close', function () {
  const dp = [];

  dp[0] = 0;
  dp[1] = 3;
  dp[2] = 7;
  dp[3] = 17;

  for (let i = 4; i <= input; i++) {
    dp[i] = (dp[i - 1] * 2 + dp[i - 2]) % 9901;
  }

  console.log(dp[input] % 9901);
});

์ „ํ˜•์ ์ธ DP๋ฌธ์ œ์ด๋‹ค. DP๋ฌธ์ œ๋Š” ๋ฉ”๋ชจ๋ฆฌ์ œํ•œ์ด ๋‚ฎ๊ฑฐ๋‚˜, ์ž…๋ ฅ๊ฐ’์ด ์ƒ๋‹นํžˆ ํฌ๋‹ค๋ฉด DP๋ฌธ์ œ์ธ์ง€ ํŒŒ์•…ํ•ด๋ณด์ž.

 

N = 0์ผ๋•Œ๋Š” ๋‹น์—ฐํžˆ ์‚ฌ์ž๊ฐ€ ๋“ค์–ด๊ฐˆ ๊ณต๊ฐ„์ด ์—†์œผ๋ฏ€๋กœ 0์ด๋‹ค.

 

N = 1์ผ๋•Œ๋Š” 2X1 ๊ณต๊ฐ„์ด ์žˆ์œผ๋ฏ€๋กœ

์‚ฌ์ž๊ฐ€ ์—†๋Š”๊ฒฝ์šฐ => 1

์‚ฌ์ž๊ฐ€ ํ•œ ๋งˆ๋ผ์ธ ๊ฒฝ์šฐ 2 => 3์ด๋‹ค.

 

N = 2์ผ๋•Œ๋Š” 2X2 ๊ณต๊ฐ„์ด ์žˆ์œผ๋ฏ€๋กœ

์‚ฌ์ž๊ฐ€ ์—†๋Š”๊ฒฝ์šฐ => 1

์‚ฌ์ž๊ฐ€ ํ•œ ๋งˆ๋ฆฌ์ธ ๊ฒฝ์šฐ => 4

์‚ฌ์ž๊ฐ€ 2๋งˆ๋ฆฌ์ธ ๊ฒฝ์šฐ => 2 => 7์ด๋‹ค.

 

N = 3์ผ๋•Œ๋Š” 2X3์˜ ๊ณต๊ฐ„์ด ์žˆ์œผ๋ฏ€๋กœ

์‚ฌ์ž๊ฐ€ ์—†๋Š”๊ฒฝ์šฐ => 1

์‚ฌ์ž๊ฐ€ ํ•œ ๋งˆ๋ฆฌ์ธ ๊ฒฝ์šฐ => 6

์‚ฌ์ž๊ฐ€ 2๋งˆ๋ฆฌ์ธ ๊ฒฝ์šฐ => 8

์‚ฌ์ž๊ฐ€ 3๋งˆ๋ฆฌ์ธ ๊ฒฝ์šฐ => 2   => 17์ด๋‹ค.

 

์—ฌ๊ธฐ๊นŒ์ง€ ๋ณด๋ฉด ์ ํ™”์‹์„ ์œ ์ถ”ํ•  ์ˆ˜ ์žˆ๋‹ค.

๊ฒฐ๊ตญ 2X3์˜ ๊ณต๊ฐ„์€ 2X2์˜ ๊ณต๊ฐ„์ด ์ค‘๋ณต์—†์ด 2๊ฐœ ๋“ค์–ด๊ฐ€๊ณ  2X1์˜ ๊ณต๊ฐ„์ด ํ•˜๋‚˜ ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ๋‹ค.

 

Fun(N) = Fun(N-1)*2 + Fun(N-2) ์ด๋ž€ ๊ฑธ ์•Œ ์ˆ˜ ์žˆ๋‹ค!

 

%9901์— ์œ ์˜ํ•˜๋ฉฐ ๋‹ต์„ ๋‚ด๋ฉด ๋์ด๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•