2022. 1. 12. 21:03ใ๐ฑ Algorithm/DP
https://www.acmicpc.net/problem/12852
์ ๋ต ์ฝ๋ (์๋ ๋น ๋ฆ)
def solution():
visited = []
queue = [[N, [N]]]
while queue:
number, path = queue.pop(0)
if number == 1:
print(queue)
print(len(path) - 1)
print(" ".join(map(str, path)))
break
if number not in visited:
visited.append(number)
if number % 3 == 0:
queue.append([number // 3, path + [number // 3]])
if number % 2 == 0:
queue.append([number // 2, path + [number // 2]])
queue.append([number - 1, path + [number - 1]])
N = int(input())
solution()
์๋์ ์๋๊ฐ ๋น๊ต์ ๋๋ฆฐ ์ ๋ต ์ฝ๋์ ๋น๊ตํ์ ๋, ์ ์ฝ๋๋ visited ๋ฐฐ์ด์ ์ด์ฉํ์ฌ ํ๋ฒ ์ฐ์ฐํ ๊ฐ์ ์ฒดํฌํ๋ค. ๊ทธ๋ฆฌํ์ฌ ๋ฐ๋ณต์ ์ธ ์ฐ์ฐ์ ๋ง๋๋ฐ, ์๋ ์ฝ๋๋ visited ๋ก ํ์ธํ๋ ๋์ , ๊ธฐ์กด์ ์ฐ์ฐ ๊ฐ( ์๋ ์ฝ๋ ๊ธฐ์ค dp[i][0])์ด ์๋ก ๊ณ์ฐ ํ ๊ฐ๋ณด๋ค ์์ผ๋ฉด ์ ๋ฐ์ดํธ ํ๋ ๋ฐฉ๋ฒ์ ํํ๋ค. ์ฆ ์ด๋ฏธ ๋ฐฉ๋ฌธํ ์ซ์์ ๋ํด์๋ ๋งค๋ฒ ๋น๊ต ์ฐ์ฐ์ ์ํํ๊ธฐ ๋๋ฌธ์ ์์ ์ฝ๋๋ณด๋ค ์๋๊ฐ ๋จ์ด์ง๋ ๊ฒ์ด๋ผ ์๊ฐํ๋ค.
์ ๋ต ์ฝ๋ (์๋ ๋๋ฆผ)
N = int(input())
dp = [[0, []] for _ in range(N + 1)]
dp[1][1] = [1]
for i in range(2, N + 1):
dp[i][0] = dp[i - 1][0] + 1
dp[i][1] = dp[i - 1][1] + [i]
if i % 3 == 0 and dp[i // 3][0] + 1 < dp[i][0]:
dp[i][0] = dp[i // 3][0] + 1
dp[i][1] = dp[i // 3][1] + [i]
if i % 2 == 0 and dp[i // 2][0] + 1 < dp[i][0]:
dp[i][0] = dp[i // 2][0] + 1
dp[i][1] = dp[i // 2][1] + [i]
print(dp[N][0])
print(*dp[N][1][::-1])
ํ๋ฆฐ ํ์ด (๋ด ์ฝ๋ ใ )
์๋ชป ์๊ฐํ ์ ์ด ์ฌ๊ท ํจ์์ ๋งค๊ฐ๋ณ์๋ก queue ๋ฅผ n ๊ณผ ๋ถ๋ฆฌํ์ฌ ๋ฃ์ ๊ฒ์ด๋ค.
์ฌ๊ท๋ก ํจ์๋ฅผ ํธ์ถํ๋ queue๋ ๋ฉํฐ์ค๋ ๋ ๋ง๋ฅ ๊ฐ๋ณ๋ก ์์ฑ๋ ๊ฒ์ด๋ผ ์๊ฐํ๋๋ฐ ๊ทธ๋ ๊ฒ ๋ ๋ฆฌ๊ฐ ์๋ค.
๋งค๋ฒ ์ฌ๊ท๋ง๋ค queue ์ ๊ฐ์ด append ๋๊ธฐ ๋๋ฌธ์ , ๊ฐ ์ซ์ n ์ ๋ํ history ๊ฐ ๋จ์ง ์๊ณ , ๋ชจ๋ ํฉ์ณ์ง history ๊ฐ ๋จ๊ฒ ๋์ด ์ค๋ต์ ์ด๋ฅด๊ฒ ๋๋ค. ์ฆ ์ด๋ฐ์์ผ๋ก ํ๊ณ ์ถ์๋ค๋ฉด ์ฌ๊ท ํจ์์ ์ธ์๋ก n ๊ณผ queue ๋ฅผ ํ๋๋ก ๋ฌถ์ด์
๋์ ธ์ผํ๋ค.
from sys import stdin
read = stdin.readline
n = int(read())
dp = [0] * (n + 1)
queue = [n]
def recursive(n, queue):
if n < 1:
return False
if n == 1:
return [n, queue]
if n % 3 == 0:
a = n // 3
dp[a] = dp[n] + 1
queue.append(a)
recursive(a, queue)
if n % 2 == 0:
a = n // 2
dp[a] = dp[n] + 1
queue.append(a)
recursive(a, queue)
a = n - 1
queue.append(a)
return recursive(a, queue)
answer = recursive(n, queue)
'๐ฑ Algorithm > DP' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค 11055 ํ์ด์ฌ (0) | 2022.01.23 |
---|---|
๋ฐฑ์ค 1912 ํ์ด์ฌ (0) | 2022.01.20 |
๋ฐฑ์ค 11053 ํ์ด์ฌ (0) | 2022.01.18 |
๋ฐฑ์ค 2293 ํ์ด์ฌ (0) | 2022.01.09 |
๋ฐฑ์ค 1699 ํ์ด์ฌ (0) | 2022.01.07 |