๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ Algorithm/์•Œ๊ณ ๋ฆฌ์ฆ˜-Python

[์•Œ๊ณ ๋ฆฌ์ฆ˜/Python] BOJ 1158 - ์š”์„ธํ‘ธ์Šค ๋ฌธ์ œ (๊ธฐ์ดˆ ์ž๋ฃŒ๊ตฌ์กฐ)

by Danna 2021. 3. 6.
728x90
728x90

BOJ ๋ฌธ์ œํŽ˜์ด์ง€

์›์—์„œ ์‚ฌ๋žŒ๋“ค์ด ์ œ๊ฑฐ๋˜๋Š” ์ˆœ์„œ๋ฅผ (N, K)-์š”์„ธํ‘ธ์Šค ์ˆœ์—ด์ด๋ผ๊ณ  ํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด (7, 3)-์š”์„ธํ‘ธ์Šค ์ˆœ์—ด์€ <3, 6, 2, 7, 5, 1, 4>์ด๋‹ค.

 

ํ’€์ด1

  • ๋‹จ์ˆœํžˆ ๋ฆฌ์ŠคํŠธ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ’€์—ˆ๋‹ค.
  • index์™€ target ๋ณ€์ˆ˜๋ฅผ ์ง€์ •ํ•ด ๋ฆฌ์ŠคํŠธ์—์„œ target ์„ ์ œ๊ฑฐํ•˜๊ณ ,
  • ๋‹ค์‹œ ํ˜„์žฌ์œ„์น˜์—์„œ k๋ฒˆ์งธ ์‚ฌ๋žŒ์ด ์ œ๊ฑฐ๋ ์ˆ˜ ์žˆ๋„๋ก index ๋ฅผ ๋ณ€๊ฒฝ์‹œ์ผฐ๋‹ค.
# BOJ-1158.py

from sys import stdin
input = stdin.readline

n, k = map(int, input().split())
nums = list(range(1, n+1))
result = []
target = k
while(True):
    index = nums.index(target)
    nums.remove(target)
    result.append(target)

    if not nums:
        break

    index += k - 1
    if index >= len(nums):
        index = index % len(nums)
    #print(target, "->", nums[index])
    target = nums[index]

print("<{}>".format(", ".join(map(str, result))))

 

 

ํ’€์ด 2

  • index ์™€ target ์€ ๊ฐ™์€ ์˜๋ฏธ์ด๋ฏ€๋กœ target ๋ณ€์ˆ˜๋ฅผ ์‚ญ์ œํ–ˆ๋‹ค.
  • ์ฝ”๋“œ๊ฐ€ ๋”์šฑ ๊ฐ„๊ฒฐํ•ด์ง!
from sys import stdin
input = stdin.readline

n, k = map(int, input().split())
nums = list(range(1, n+1))
index = k - 1
result = []
while(True):
    result.append(nums.pop(index))
    if not nums:
        break
    index += k - 1
    if index >= len(nums):
        index = index % len(nums)

print("<{}>".format(", ".join(map(str, result))))

 

 

ํ’€์ด3

  • ํ’€์ด2์™€ ๋ฉ”๋ชจ๋ฆฌ, ์‹œ๊ฐ„์€ ๋˜‘๊ฐ™์Œ
  • index ๋‚˜๋ˆ„๊ธฐ ์—ฐ์‚ฐ์„ ๊ตณ์ด if ๋ฌธ์œผ๋กœ ํ™•์ธํ•˜์ง€ ์•Š๊ณ  ์‚ฌ์šฉํ•ด๋„ ๋œ๋‹ค.
    • ์—ฐ์‚ฐ ์ˆœ์„œ๋ฅผ ๋ฐ”๊ฟ”์•ผํ•จ
    • index ๋‚˜๋ˆ„๊ธฐ ์—ฐ์‚ฐ → pop → index ์ด๋™
  • ๋ฐ˜๋ณตํšŸ์ˆ˜๋Š” n๋งŒํผ ๋ฐ˜๋ณต๋œ๋‹ค.
    • ํ’€์ด2์—์„œ์˜ While, if not ๋ถˆ ํ•„์š”ํ•จ.
from sys import stdin
input = stdin.readline

n, k = map(int, input().split())
nums = list(range(1, n+1))
index = k - 1
result = []
for _ in range(n):
    index = index % len(nums)    
    result.append(nums.pop(index))
    index += k - 1

print("<{}>".format(", ".join(map(str, result))))

BOJ ๋งํฌ

728x90
728x90