[๋ฐฑ์ค€/python] 1463๋ฒˆ : 1๋กœ ๋งŒ๋“ค๊ธฐ

2021. 7. 29. 09:28

๋ฌธ์ œ

์ •์ˆ˜ X์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์—ฐ์‚ฐ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์„ธ ๊ฐ€์ง€ ์ด๋‹ค.

  1. X๊ฐ€ 3์œผ๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋ฉด, 3์œผ๋กœ ๋‚˜๋ˆˆ๋‹ค.
  2. X๊ฐ€ 2๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋ฉด, 2๋กœ ๋‚˜๋ˆˆ๋‹ค.
  3. 1์„ ๋บ€๋‹ค.

์ •์ˆ˜ N์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ์œ„์™€ ๊ฐ™์€ ์—ฐ์‚ฐ ์„ธ ๊ฐœ๋ฅผ ์ ์ ˆํžˆ ์‚ฌ์šฉํ•ด์„œ 1์„ ๋งŒ๋“ค๋ ค๊ณ  ํ•œ๋‹ค. ์—ฐ์‚ฐ์„ ์‚ฌ์šฉํ•˜๋Š” ํšŸ์ˆ˜์˜ ์ตœ์†Ÿ๊ฐ’์„ ์ถœ๋ ฅํ•˜์‹œ์˜ค.

 

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 106๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค.

 

์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ์—ฐ์‚ฐ์„ ํ•˜๋Š” ํšŸ์ˆ˜์˜ ์ตœ์†Ÿ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค.

 

์ •๋‹ต

import sys
from collections import defaultdict

number = int(sys.stdin.readline())
count = defaultdict(lambda : 999999)
count[1], count[2], count[3] = 0, 1, 1

for n in range(4, number+1):
    if n%3 == 0 and n%2 == 0:
        count[n] = min(count[n//3], count[n//2], count[n-1]) + 1
    elif n%3 == 0:
        count[n] = min(count[n//3], count[n-1]) + 1
    elif n%2 == 0:
        count[n] = min(count[n//2], count[n-1]) + 1
    else:
        count[n] = count[n-1] + 1

print(count[number])

์ž…๋ ฅ๋ฐ›์€ ์ˆซ์ž number์—์„œ 1๋กœ ๋‚ด๋ ค๊ฐ€๋Š” ๊ฒƒ์ด ์•„๋‹Œ

1์—์„œ number๋กœ ์˜ฌ๋ผ๊ฐ€๋Š” ๋ฐฉ์‹์œผ๋กœ ํ’€์ดํ–ˆ๋‹ค.

 

defaultdict๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ€์žฅ ํฐ ์ˆ˜๋กœ ์ดˆ๊ธฐํ™”ํ•ด๋†“๊ณ 

2์™€ 3์€ ๋ฌด์กฐ๊ฑด 1๋ฒˆ์ด๋ฏ€๋กœ 1๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.

 

๊ฐ’์„ ๋ชจ๋ฅด๋Š” 4๋ถ€ํ„ฐ number๊นŒ์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ๋ฒ”์œ„๋ฅผ 4, number+1๋กœ ์ง€์ •ํ•˜์—ฌ ๋ฐ˜๋ณตํ•œ๋‹ค.

3์œผ๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ๊ฒฝ์šฐ์™€ 2๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ๊ฒฝ์šฐ๋ฅผ ๊ณ ๋ คํ•˜์—ฌ

3์œผ๋กœ ๋‚˜๋ˆˆ ๊ฐ’, 2๋กœ ๋‚˜๋ˆˆ ๊ฐ’, 1์„ ๋บ€ ๊ฐ’์˜ count ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์—์„œ 1์„ ๋”ํ•˜์—ฌ count์— ์ €์žฅํ•œ๋‹ค.

 

๋งˆ์ง€๋ง‰์œผ๋กœ number์— ๋„๋‹ฌํ•˜๊ธฐ ๊นŒ์ง€ ํšŸ์ˆ˜์ธ count[number]์„ ์ถœ๋ ฅํ•œ๋‹ค.

728x90

BELATED ARTICLES

more