ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [๋ฐฑ์ค€] 9934 ์™„์ „ ์ด์ง„ ํŠธ๋ฆฌ with Python
    PS 2021. 9. 12. 23:18
    728x90
    ๋ฐ˜์‘ํ˜•

    ๐Ÿ“Œ BOJ 9934 ์™„์ „ ์ด์ง„ ํŠธ๋ฆฌ

    ๐Ÿ’ก ์กฐ๊ฑด ๋ฐ ํ’€์ด

    1. ์ด์ง„ ํŠธ๋ฆฌ์˜ ๊นŠ์ด๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” 1<=K<=10, ๊นŠ์ด๊ฐ€ K์ธ ์ด์ง„ ํŠธ๋ฆฌ๋Š” ์ด 2 * K - 1 ๊ฐœ์˜ ๋…ธ๋“œ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.
    2. ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰ ๋ ˆ๋ฒจ์„ ์ œ์™ธํ•œ ๋ชจ๋“  ์ง‘์€ ์™ผ์ชฝ ์ž์‹๊ณผ ์˜ค๋ฅธ์ชฝ ์ž์‹์„ ๊ฐ–๋Š”๋‹ค.
    3. ์ด๋ถ„ํƒ์ƒ‰, ํŠธ๋ฆฌ, ์žฌ๊ท€๊ตฌํ˜„ ๋ฌธ์ œ
    4. ๋ชจ๋“  ๋นŒ๋”ฉ์˜ ๋ฒˆํ˜ธ๋Š” ์ค‘๋ณต๋˜์ง€ ์•Š๋Š”๋‹ค.

    ๐Ÿ–ฅ ์†Œ์Šค ์ฝ”๋“œ

    from sys import stdin, setrecursionlimit
    setrecursionlimit(int(1e9))
    k = int(stdin.readline())
    arr = list(map(int, stdin.readline().split()))
    res = [[] for _ in range(k)]
    
    
    def binary_separation(arr, depth):
        if len(arr) == 1:
            res[depth].extend(arr)
            return
    
        length = len(arr)
        mid = length // 2
        res[depth].append(arr[mid])
        binary_separation(arr[:mid], depth + 1)
        binary_separation(arr[mid + 1:], depth + 1)
    
    
    binary_separation(arr, 0)
    
    for i in range(k):
        if i == 0:
            print(res[i][0])
        else:
            print(*res[i])

    ๐Ÿ”– ์˜ˆ์ œ ๋ฐ ์‹คํ–‰๊ฒฐ๊ณผ

    ์˜ˆ์ œ

    3
    1 6 4 3 5 2 7

    ์‹คํ–‰๊ฒฐ๊ณผ

    3
    6 2
    1 4 5 7

    โŒจ๏ธ ๋ฌธ์ œ ํ’€์ด

    1. ๊นŠ์ด๊ฐ€ k ์ธ 2์ฐจ์› ๋ฆฌ์ŠคํŠธ res ๋ฅผ ์ƒ์„ฑํ•˜๊ณ , ์ด ๋ฆฌ์ŠคํŠธ์— ๋…ธ๋“œ๋ฅผ ์Œ“์„ ๊ฒƒ์ž…๋‹ˆ๋‹ค.
    2. Python ๋ฆฌ์ŠคํŠธ ์ž๋ฃŒ๊ตฌ์กฐ์˜ extend() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.
      extend๋Š” ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฆฌ์ŠคํŠธ ์•ˆ์œผ๋กœ ๋„ฃ์„ ๋•Œ ๋ฆฌ์ŠคํŠธ์˜ ์›์†Œ๋งŒ ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.
    3. ์ž…๋ ฅ๋ฐ›์€ ๋นŒ๋”ฉ๋ฒˆํ˜ธ์˜ ๊ธธ์ด๋ฅผ 2๋กœ ๋‚˜๋ˆ„์–ด ๊ฐ’์„ mid ๋ณ€์ˆ˜์— ๋„ฃ์–ด ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.
    4. res์— ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›์€ depth ๊ฐ’์„ ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.
      ๊ฐ€์žฅ ๋งจ ์ฒ˜์Œ์œผ๋กœ ์ด๋ถ„ํƒ์ƒ‰์„ ํ†ตํ•ด ๋ฝ‘์•„๋‚ธ ๊ฐ€์šด๋ฐ ๊ฐ’์ด ๋ฃจํŠธ ๋…ธ๋“œ์ž…๋‹ˆ๋‹ค.
    5. ๊ฐ€์šด๋ฐ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ์–‘์ชฝ์„ ๋ถ„๋ฆฌํ•ด ๊ฐ๊ฐ ๋‹ค์‹œ ์ด๋ถ„ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.
    6. ์ด๋ถ„ ํƒ์ƒ‰์„ ํ•˜๋‹ค๊ฐ€, ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ›์€ arr ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด๊ฐ€ 1์ธ ๊ฒฝ์šฐ depth ์— ํ•ด๋‹นํ•˜๋Š”
      ๋ฆฌ์ŠคํŠธ์— ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.
    7. ๋งŒ๋“ค์–ด์ง„ ํŠธ๋ฆฌ(res)๋ฅผ ์ถœ๋ ฅํ•ด์ค๋‹ˆ๋‹ค.
    8. ํŒŒ์ด์ฌ์œผ๋กœ ์žฌ๊ท€๋ฅผ ๊ตฌํ˜„ํ•  ๋•Œ,์•„๋ž˜์˜ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ์—๋Ÿฌ๊ฐ€ ๋‚˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ์Šต๋‹ˆ๋‹ค.
      ์“ด๋‹ค๊ณ  ๋ฌธ์ œ๋  ๊ฒƒ์ด ์—†์œผ๋‹ˆ, ์žฌ๊ท€๋ฅผ ๊ตฌํ˜„ํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ‘ธ์‹ค ๋•Œ ๊ผญ ์ž…๋ ฅํ•˜์„ธ์š”.
       
    9. setrecursionlimit(int(1e9))โ€‹

    ๐Ÿ’พ ๋Š๋‚€์ 

    • ์ด๋ถ„ํƒ์ƒ‰๊ณผ ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ‘ธ๋Š” ๋ฐฉ์‹์— ์ต์ˆ™ํ•ด์ง„ ๊ฒƒ์„ ๋Š๊ผˆ๋‹ค.
    • ๋ถ„ํ•  ์ •๋ณต ๋ฌธ์ œ๋ฅผ ํ’€๋‹ค๊ฐ€ ์ด ๋ฌธ์ œ๋ฅผ ํ‘ธ๋‹ˆ ํ›จ์”ฌ ๋„์›€์ด ๋˜์—ˆ๋‹ค.
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€

Designed by Tistory.