๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/๋ฐฑ์ค€(BOJ)

[ ํŒŒ์ด์ฌ(python) ] ๋ฐฑ์ค€ 1158 - ์š”์„ธํ‘ธ์Šค ๋ฌธ์ œ

by YWTechIT 2021. 5. 4.
728x90

๐Ÿ“Œ ๋ฐฑ์ค€ 1158 - ์š”์„ธํ‘ธ์Šค ๋ฌธ์ œ

๋ฌธ์ œ ์„ค๋ช…


๐Ÿ’ก ๋‚˜์˜ ํ’€์ด

์š”์„ธํ‘ธ์Šค ๋ฌธ์ œ๋Š” ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ(linkedList)๋กœ ํ’€ ์ˆ˜ ์žˆ๋Š” ์ „ํ˜•์ ์ธ ๋ฌธ์ œ์ด์ง€๋งŒ ํ(queue)๋ฅผ ์‚ฌ์šฉํ•ด์„œ๋„ ํ’€ ์ˆ˜ ์žˆ๋‹ค.

 

  1. k๋ฒˆ์งธ์˜ ์‚ฌ๋žŒ๋“ค์ด ๊ณ„์†ํ•ด์„œ ์ œ๊ฑฐ๋˜์–ด์•ผ ํ•˜๋ฏ€๋กœ cnt๋ฅผ 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.
  2. len(arr)์ด 0์ด๋ ๋•Œ๊นŒ์ง€ ์ œ์ผ ์•ž์— ์žˆ๋Š” ์ˆ˜๊ฐ€ ์ œ์ผ ๋’ค๋กœ ์ด๋™ํ•˜๋ฉด์„œ ์ˆœํ™˜ํ•œ๋‹ค.
  3. ํ•œ๋ฒˆ ์ˆœํ™˜ ํ• ๋•Œ๋งˆ๋‹ค cnt๊ฐ€ 1์”ฉ ๋ˆ„์ ๋œ๋‹ค.
  4. ๋งŒ์•ฝ, cnt๊ฐ€ k-1์™€ ๊ฐ™๋‹ค๋ฉด ๋‹ค์Œ ์‚ฌ๋žŒ์ด ์ œ๊ฑฐ๋˜์•ผํ•˜๋ฏ€๋กœ ํ•ด๋‹น ์ˆ˜๋ฅผ stack์— ์ถ”๊ฐ€ํ•œ๋‹ค.(์ธ๋ฑ์Šค๋Š” 0๋ถ€ํ„ฐ ์„ธ๋ฏ€๋กœ k-1๋กœ ์„ ์–ธํ–ˆ๋‹ค.)
  5. stack์œผ๋กœ ๋น ์กŒ๋‹ค๋ฉด ๋‹ค์‹œ 0๋ถ€ํ„ฐ ์นด์šดํŠธํ•œ๋‹ค.

 

๊ทธ๋Ÿด์‹ธํ•œ ๋กœ์ง์ด๋‹ค. ํ•˜์ง€๋งŒ, ์ด๋Œ€๋กœ ์ œ์ถœํ•˜๋ฉด ์‹คํ–‰์‹œ๊ฐ„์ด ๋น„์•ฝ์ ์œผ๋กœ ๋†’๊ฒŒ ๋‚˜์˜จ๋‹ค.

๊ทธ๋ž˜์„œ ๋‹ค์Œ ์ œ๊ฑฐํ•  ์‚ฌ๋žŒ์˜ ์ธ๋ฑ์Šค๋ฅผ ์ฐพ์„ ๋•Œ (k-1) mod N๋ฒˆ ํฌ์ธํ„ฐ๋ฅผ ๋ˆ„์ ํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ–ˆ๋‹ค. ์ด ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ฉด ์‹คํ–‰์‹œ๊ฐ„์ด ๋‹จ์ถ•๋œ๋‹ค.

# ๋‚˜์˜ ์ฝ”๋“œ(cnt)
import sys
from collections import deque
input = sys.stdin.readline

n, k = map(int, input().split())
arr = deque(range(1, n + 1))
stack = []
cnt = 0

while arr:
    if cnt == k-1:
        stack.append(arr.popleft())
        cnt = 0
    else:
        arr.append(arr.popleft())
        cnt += 1

print(f"<{', '.join(map(str, stack))}>")
# ๋‹ค๋ฅธ์‚ฌ๋žŒ์˜ ์ฝ”๋“œ(k-1 mod N)
import sys
input = sys.stdin.readline

n, k = map(int, input().split())
arr = list(range(1, n + 1))
stack = []
cnt = 0

while arr:
    cnt = (cnt+(k-1)) % len(arr)
    stack.append(arr.pop(cnt))

print(f"<{', '.join(map(str, stack))}>")
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€