Post

๐Ÿข ํŠธ๋ฆฌ์˜ ์ˆœํšŒ

1. ๋ฌธ์ œ ๋งํฌ

16509๋ฒˆ: ํŠธ๋ฆฌ์˜ ์ˆœํšŒ


2. ์ฝ”๋“œ

Python3 72364KB 412ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
[2263] ํŠธ๋ฆฌ์˜ ์ˆœํšŒ

๐Ÿ’› ๋ฌธ์ œ
n๊ฐœ์˜ ์ •์ ์„ ๊ฐ–๋Š” ์ด์ง„ ํŠธ๋ฆฌ์˜ ์ •์ ์— 1๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ค‘๋ณต ์—†์ด ๋งค๊ฒจ์ ธ ์žˆ๋‹ค.
์ด์™€ ๊ฐ™์€ ์ด์ง„ ํŠธ๋ฆฌ์˜ ์ธ์˜ค๋”์™€ ํฌ์ŠคํŠธ์˜ค๋”๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ํ”„๋ฆฌ์˜ค๋”๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

๐Ÿ’š ์ž…๋ ฅ
์ฒซ์งธ ์ค„์— n(1 โ‰ค n โ‰ค 100,000)์ด ์ฃผ์–ด์ง„๋‹ค.
๋‹ค์Œ ์ค„์—๋Š” ์ธ์˜ค๋”๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” n๊ฐœ์˜ ์ž์—ฐ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๊ณ ,
๊ทธ ๋‹ค์Œ ์ค„์—๋Š” ๊ฐ™์€ ์‹์œผ๋กœ ํฌ์ŠคํŠธ์˜ค๋”๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

๐Ÿ’™ ์ถœ๋ ฅ
์ฒซ์งธ ์ค„์— ํ”„๋ฆฌ์˜ค๋”๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.
"""

# 1) ํ›„์œ„์ˆœํšŒ์—์„œ ๋งˆ์ง€๋ง‰์— ์˜ค๋Š” ๊ฐ’์€ ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ
# 2) ์ค‘์œ„์ˆœํšŒ์—์„œ ๋ฃจํŠธ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์™ผ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ์™€ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ
# 3) ํ›„์œ„์ˆœํšŒ๋ฅผ ์ค‘์œ„์ˆœํšŒ์™€ ๊ฐ™์ด ๋‚˜๋ˆˆ ํ›„ ๊ฐ ์„œ๋ธŒ ํŠธ๋ฆฌ์—์„œ ๋งˆ์ง€๋ง‰์— ์˜ค๋Š” ๊ฐ’์€ ์„œ๋ธŒ ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ

# ํŒŒ์ด์ฌ์˜ ์žฌ๊ท€ ์ตœ๋Œ€ ๊นŠ์ด์˜ ๊ธฐ๋ณธ ์„ค์ •์ด 1,000ํšŒ ์ด๊ธฐ ๋•Œ๋ฌธ์— ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒ
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

n = int(input())
inorder = list(map(int, input().split()))
postorder = list(map(int, input().split()))

# inorder์˜ ๊ฐ’ index ๋ฆฌ์ŠคํŠธ
inorder_pos = [0] * (n+1)

def preorder(inorder_s, inorder_e, postorder_s, postorder_e):
    # ์žฌ๊ท€ํ•จ์ˆ˜ ์ข…๋ฃŒ ์กฐ๊ฑด
    if (inorder_s > inorder_e) or (postorder_s > postorder_e):
        return

    # ํ›„์œ„ ์ˆœํšŒ์˜ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ ์ถœ๋ ฅ
    p = postorder[postorder_e]
    print(p, end =' ')

    # ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜
    left = inorder_pos[p] - inorder_s

    # ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜
    right = inorder_e - inorder_pos[p]

    # ์™ผ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ
    preorder(inorder_s, inorder_s+left-1, postorder_s, postorder_s+left-1)
    # ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ
    preorder(inorder_e - right + 1, inorder_e, postorder_e - right, postorder_e - 1)


# ํ›„์œ„์ˆœํšŒ์˜ ๋งˆ์ง€๋ง‰๊ฐ’์ด ์ค‘์œ„์ˆœํšŒ ๋ช‡๋ฒˆ์งธ์— ์กด์žฌํ•˜๋Š”์ง€ ์•Œ๊ธฐ ์œ„ํ•ด
for i in range(n):
    inorder_pos[inorder[i]] = i

preorder(0, n-1, 0, n-1)


3. ํ•ด์„ค

This post is licensed under CC BY 4.0 by the author.