ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

1158๋ฒˆ: ์š”์„ธํ‘ธ์Šค ๋ฌธ์ œ

์ฒซ์งธ ์ค„์— N๊ณผ K๊ฐ€ ๋นˆ ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ˆœ์„œ๋Œ€๋กœ ์ฃผ์–ด์ง„๋‹ค. (1 ≤ K ≤ N ≤ 5,000)

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ํ•ด๋‹น ๋ฌธ์ œ๋ฅผ ๋ณด๊ณ  ์ฒ˜์Œ์— ๋“œ๋Š” ์ƒ๊ฐ์€ ์›ํ˜• ํ ๋ฌธ์ œ์ธ๊ฐ€? ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค. ํ•˜์ง€๋งŒ ์ˆœํšŒํ•˜๋ฉด์„œ pop์„ ํ•˜๊ณ ์ž ํ•˜๋Š” index์— ์œ„์น˜ํ•˜๋Š” ๊ฐ’์„ ์ œ๊ฑฐํ•˜๋Š” ๊ฒƒ์€ ๋‹ค์†Œ ๋น„ํšจ์œจ์ ์ด๋‹ค. 

 

from collections import deque


def solution(k, n):
    mans = deque([num + 1 for num in range(k)])
    answer = []
    cnt = n
    while mans:
        if cnt:
            mans.append(mans.popleft())
            cnt -= 1
        else:
            answer.append(str(mans.popleft()))
            cnt = n

    return answer

 ์œ„์˜ ์ฝ”๋“œ ์ฒ˜๋Ÿผ ์›ํ˜• ํ๋ฅผ ์ˆœํšŒ ํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๊ณ  ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๋ฐฉ์‹์„ ๊ตฌํ˜„ํ•˜์—ฌ ์ •๋‹ต์„ ์ œ์ถœํ•˜๋ฉด ์–ด๋–จ๊นŒ? deque๋ฅผ ์ด์šฉํ•ด list์˜ pop์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ์˜ค๋ฒ„ํ—ค๋“œ๊ฐ€ ์ค„๊ฒ ์ง€... ํ•˜๊ณ  ์ œ์ถœํ•ด๋ณด์•˜๋‹ค.๐Ÿ˜ฎ

๊ฒฐ๊ณผ๋Š” ์ข‹์ง€ ์•Š๋‹ค...๐Ÿ˜“ ๋ฌธ์ œ๋Š” ๋งž์ถœ ์ˆ˜ ์žˆ์ง€๋งŒ ์‹œ๊ฐ„์ด ๋ฌด๋ ค 3284ms๊ฐ€ ๊ฑธ๋ฆฐ๋‹ค. ๋‹ค์‹œ ๊ฐ€๋งŒํžˆ ์ƒ๊ฐํ•ด๋ณด๋ฉด list์˜ ์›์†Œ๋“ค์„ rotation์‹œํ‚ฌ ๊ฒฝ์šฐ, %๋ฅผ ํ†ตํ•ด ์ฒ˜๋ฆฌํ•˜๋Š”๋ฐ ์ด๊ฒƒ๋„ ๊ทธ ๋ฌธ์ œ์ธ๊ฐ€? ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค.

 

์ฆ‰, ๋ฌธ์ œ ํ’€์ด๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ ‘๊ทผํ•˜๋ฉด ๋œ๋‹ค.

  • ์›ํ˜• ํ์™€ ๊ฐ™์ด ์ƒ๊ฐํ•˜๊ณ  ์ ‘๊ทผํ•˜์—ฌ๋„ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐ ํ•  ์ˆ˜ ์žˆ๋‹ค.
    • ํŒŒ์ด์ฌ์ด ์•„๋‹Œ ๋‹ค๋ฅธ ์–ธ์–ด๋ผ๋ฉด ์‹œ๊ฐ„์ด ๋” ์งง๊ฒŒ ๋‚˜์˜ฌ ์ˆ˜๋„ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•œ๋‹ค.
  • list์˜ ์›์†Œ๋ฅผ rotationํ•˜๋Š” ๋ฌธ์ œ๋“ค ์ฒ˜๋Ÿผ, % ์—ฐ์‚ฐ์„ ํ™œ์šฉํ•˜์—ฌ index์˜ ๊ฐ’์„ ๋ฐ”๋กœ๋ฐ”๋กœ ๋„์ถœํ•˜๋ฉด ๋œ๋‹ค.

 

์ฝ”๋“œ

import sys


def solution(k, n):
    mans = [num + 1 for num in range(k)]
    answer = []
    pop_idx = 0

    while mans:
        pop_idx = (pop_idx + n) % len(mans)
        answer.append(str(mans.pop(pop_idx)))

    return answer

if __name__ == "__main__":
    k, n = map(int, sys.stdin.readline().split())
    print("<%s>" %(", ".join(solution(k, n - 1))))

์›ํ˜• ํ๋ฅผ ํ†ตํ•ด ์ „์ฒด๋ฅผ ์ˆœํšŒํ•˜๋Š” ๋ฐฉ์‹๊ณผ ๋‹ฌ๋ฆฌ ํ›จ์”ฌ ํšจ์œจ์ ์œผ๋กœ ๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€