๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] 01ํƒ€์ผ BOJ #1904

by seolhee2750 2021. 11. 16.
๋ฌธ์ œ

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

 

1904๋ฒˆ: 01ํƒ€์ผ

์ง€์›์ด์—๊ฒŒ 2์ง„ ์ˆ˜์—ด์„ ๊ฐ€๋ฅด์ณ ์ฃผ๊ธฐ ์œ„ํ•ด, ์ง€์›์ด ์•„๋ฒ„์ง€๋Š” ๊ทธ์—๊ฒŒ ํƒ€์ผ๋“ค์„ ์„ ๋ฌผํ•ด์ฃผ์…จ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ด ๊ฐ๊ฐ์˜ ํƒ€์ผ๋“ค์€ 0 ๋˜๋Š” 1์ด ์“ฐ์—ฌ ์žˆ๋Š” ๋‚ฑ์žฅ์˜ ํƒ€์ผ๋“ค์ด๋‹ค. ์–ด๋Š ๋‚  ์ง“๊ถ‚์€ ๋™์ฃผ๊ฐ€ ์ง€์›์ด

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
n = int(input())
if n == 1: print(1)
elif n == 2: print(2)
else:
    memory = [1, 2]
    for i in range(2, n):
        memory.append((memory[i-2] + memory[i-1]) % 15746)
    print(memory[n-1])

๐Ÿ‘‰DP ๋ฌธ์ œ๋กœ, ์ ํ™”์‹๊ณผ ๋ฉ”๋ชจ์ด์ œ์ด์…˜ ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜์—ฌ ํ‘ธ๋Š”๊ฒŒ ํฌ์ธํŠธ!

 

[์ ํ™”์‹]

  • n == 1 : 1
  • n == 2 : 00, 11
  • n == 3 : 001, 100, 111
  • n == 4 : 0000, 0011, 1001, 1111
  • n == 5 : 00001, 00111, 10011, 11001, 11100, 00100, 11111

=> n์˜ ๊ฐœ์ˆ˜ = (n-1)์˜ ๊ฐœ์ˆ˜ + (n-2)์˜ ๊ฐœ์ˆ˜

 

[ํ’€์ด ์„ค๋ช…]

  • n์ด 1 ํ˜น์€ 2์˜ ๊ฒฝ์šฐ๋Š” ๋ฐ˜๋ณต ์—ฐ์‚ฐ์ด ๋ถˆ๊ฐ€ํ•˜๋ฏ€๋กœ ๋”ฐ๋กœ ๋นผ์„œ ์ถœ๋ ฅํ–ˆ๋‹ค.
  • ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ๋Š” ๋ชจ๋‘ for๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ memory ๋ฆฌ์ŠคํŠธ์— ๊ฐ’์„ ๋ˆ„์ ํ•˜์—ฌ ๊ฒฐ๊ณผ๋ฅผ ๊ตฌํ•ด์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ๋น„๊ต์  ํ”ํ•œ ์ ํ™”์‹ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ๋ผ ๊ธˆ๋ฐฉ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

 

 

๋Œ“๊ธ€