Updated:

1. 문제 링크

https://www.acmicpc.net/problem/2263

2. 사용 알고리즘

분할정복

3. 풀이

1번~5번 원판을 1 -> 3으로 이동하는 경우

1) 1번~4번 원판을 1 -> 2로 이동

2) 5번 원판을 1 -> 3으로 이동

3) 1번~4번 원판을 2 -> 3으로 이동

재귀를 통해 1) ~ 3)번 과정 반복

4. 소스 코드

4-1. C++

https://github.com/dev-aiden/problem-solving/blob/main/boj/2263.cpp

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
#include <iostream>

using namespace std;

int inorder[100003], postorder[100003];

void solve(int inStart, int inEnd, int postStart, int postEnd) {
    if (inStart > inEnd || postStart > postEnd) return;
    int rootIndex;
    for(int i = inStart; i <= inEnd; ++i) {
        if(inorder[i] == postorder[postEnd]) {
            rootIndex = i;
            break;
        }
    }
    cout << postorder[postEnd] <<  " ";
    solve(inStart, rootIndex - 1, postStart, postStart + rootIndex - inStart - 1);
    solve(rootIndex + 1, inEnd, postStart + rootIndex - inStart, postEnd - 1);
}

int main(void) {
    int n; cin >> n;
    for(int i = 0; i < n; ++i) cin >> inorder[i];
    for(int i = 0; i < n; ++i) cin >> postorder[i];
    solve(0, n - 1, 0, n - 1);
    cout << "\n";
    return 0;
}

4-2. JAVA

https://github.com/dev-aiden/problem-solving/blob/main/boj/2263.java

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

    static int[] inorder = new int[100003];
    static int[] postorder = new int[100003];
    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());
        for(int i = 0; i < n; ++i) inorder[i] = Integer.parseInt(st.nextToken());
        st = new StringTokenizer(br.readLine());
        for(int i = 0; i < n; ++i) postorder[i] = Integer.parseInt(st.nextToken());
        solve(0, n - 1, 0, n - 1);
        sb.append("\n");
        System.out.println(sb);
    }

    static void solve(int inStart, int inEnd, int postStart, int postEnd) {
        if(inStart > inEnd || postStart > postEnd) return;
        int rootIndex = 0;
        for(int i = inStart; i <= inEnd; ++i) {
            if(inorder[i] == postorder[postEnd]) {
                rootIndex = i;
                break;
            }
        }
        sb.append(postorder[postEnd]).append(" ");
        solve(inStart, rootIndex - 1, postStart, postStart + rootIndex - inStart - 1);
        solve(rootIndex + 1, inEnd, postStart + rootIndex - inStart, postEnd - 1);
    }

}

Updated:

Leave a comment