๋ฌธ์
https://www.acmicpc.net/problem/1463
๋ฌธ์ ํ์ด
dp๋ก ์ ๊ทผํ์ง ์์ผ๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋๋ ๋ฌธ์ ์๋ค.
๋ฌธ์ ํ์ด์ ํต์ฌ์ ์๋ ์ ํ์์ด๋ค.
์ฌ๊ธฐ์ dp[i] ๋ i๋ฅผ ๋ง๋ค๊ธฐ ์ํด์ ํ์ํ ์ฐ์ฐ ํ์์ด๋ค. ( dp[1]=0, dp[2]=1, dp[3]=1 ์ด๋ค )
1 ) i๊ฐ 3์๋ฐฐ์์ด๊ณ 2์ ๋ฐฐ์์ผ ๋
dp[i] = Math. ( dp[i/3] +1 , dp[i/2] +1 , dp[i-1] +1 )
2 ) i๊ฐ 3์ ๋ฐฐ์์ด๊ณ 2์ ๋ฐฐ์๊ฐ ์๋๋
dp[i] = Math. ( dp[i/3] +1 , dp[i-1] +1 )
3 ) i๊ฐ 2์ ๋ฐฐ์์ด๊ณ 3์ ๋ฐฐ์๊ฐ ์๋๋
dp[i] = Math. ( dp[i/2] +1 , dp[i-1] +1 )
let fs = require("fs");
let input = fs.readFileSync("/dev/stdin").toString().trim();
let num = Number(input);
if (num === 1) {
console.log(0);
return;
}
let dp = Array(num + 1).fill(Infinity);
dp[1] = 0;
dp[2] = 1;
dp[3] = 1;
for (let i = 4; i <= num; ++i) {
dp[i] = dp[i - 1] + 1;
if (i % 3 === 0) {
dp[i] = Math.min(dp[i], dp[i / 3] + 1);
}
if (i % 2 === 0) {
dp[i] = Math.min(dp[i], dp[i / 2] + 1);
}
}
console.log(dp[num]);
'๐Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค[node.js] > 11727๋ฒ 2xn ํ์ผ๋ง 2 (0) | 2024.12.15 |
---|---|
๋ฐฑ์ค[node.js] > 30804๋ฒ ๊ณผ์ผ ํํ๋ฃจ (0) | 2024.12.14 |
๋ฐฑ์ค[node.js] > 1541๋ฒ ์์ด๋ฒ๋ฆฐ ๊ดํธ (0) | 2024.12.11 |
๋ฐฑ์ค[node.js] > 17129๋ฒ ๋น๋ฐ๋ฒํธ ์ฐพ๊ธฐ (0) | 2024.12.09 |
๋ฐฑ์ค[node.js] > 12865๋ฒ ํ๋ฒํ ๋ฐฐ๋ญ (0) | 2024.12.08 |