๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][๋ฐฑ์ค€] 2263 ํŠธ๋ฆฌ์˜ ์ˆœํšŒ

๋ฐ˜์‘ํ˜•

[BOJ] 2263 ํŠธ๋ฆฌ์˜ ์ˆœํšŒ

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

๋ฌธ์ œ ์ ‘๊ทผ

์ธ์˜ค๋”์™€ ํฌ์ŠคํŠธ์˜ค๋” ์ˆœํšŒ๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ ํ”„๋ฆฌ์˜ค๋” ์ˆœํšŒ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.
ํฌ์ŠคํŠธ์˜ค๋”์—์„œ๋Š” ํŠธ๋ฆฌ์™€ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋ฃจํŠธ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๊ณ , ์ธ์˜ค๋”์—์„œ๋Š” ํฌ์ŠคํŠธ์˜ค๋”์—์„œ ๊ตฌํ•œ ๋ฃจํŠธ๋ฅผ ์ด์šฉํ•˜์—ฌ ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์™€ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด๋ฅผ ์ด์šฉํ•ด์„œ ํ”„๋ฆฌ์˜ค๋” ์ˆœํšŒ๋ฅผ ๊ตฌํ•˜์˜€๋‹ค.

Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BOJ2263 {
    static int n,idx = 0;
    static int[] inorder, preorder, postorder;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        String[] input = br.readLine().split(" ");
        inorder = new int[n];
        postorder = new int[n];
        preorder = new int[n];
        // ์ž…๋ ฅ ๋ฐ›๊ธฐ
        for(int i=0; i<n; i++){
            inorder[i] = Integer.parseInt(input[i]);
        }
        input = br.readLine().split(" ");
        for(int i=0; i<n; i++){
            postorder[i] = Integer.parseInt(input[i]);
        }
        getPreorder(0,n-1,0,n-1);
        for(int num : preorder){
            System.out.print(num+" ");
        }
    }

    /**
     * postorder[pe]๊ฐ€ ์„œ๋ธŒ ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ์ด๊ณ , inorder๋Š” ์ด ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ์™ผ์ชฝ ์ž์‹๊ณผ ์˜ค๋ฅธ์ชฝ ์ž์‹์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.
     * ํŠธ๋ฆฌ๋ฅผ ๋ฃจํŠธ ๊ธฐ์ค€์œผ๋กœ ์™ผ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ์™€ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ๋กœ ๋…ธ๋“œ๊ฐ€ 1๊ฐœ์ผ ๋•Œ๊นŒ์ง€ ์ชผ๊ฐ ๋‹ค.
     * @param is inorder ์‹œ์ž‘ ์ธ๋ฑ์Šค
     * @param ie inorder ๋ ์ธ๋ฑ์Šค
     * @param ps postorder ์‹œ์ž‘ ์ธ๋ฑ์Šค
     * @param pe postorder ๋ ์ธ๋ฑ์Šค
     */
     public static void getPreorder(int is, int ie, int ps, int pe){
        if(is <= ie && ps <= pe){
            preorder[idx++] = postorder[pe];
            int pivot = is;
            for(int i = is; i<=ie; i++){
                if(inorder[i] == postorder[pe]){
                    pivot = i;
                    break;
                }
            }
            // pivot - is == ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋…ธ๋“œ ๊ฐœ์ˆ˜
            // ์™ผ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ
            getPreorder(is,pivot-1,ps, ps + pivot - is -1);
            // ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ
            getPreorder(pivot+1,ie,ps + pivot - is,pe-1);
        }
     }

}

์–ด๋ ค์› ๋˜ ์  / ๋ฐฐ์šด ์  / ๋Š๋‚€ ์ 

ํŠธ๋ฆฌ ์ˆœํšŒ๋ฌธ์ œ๋Š” ํ’€์–ด๋ดค์ง€๋งŒ ์ธ์˜ค๋”์™€ ํฌ์ŠคํŠธ์˜ค๋” ํ”„๋ฆฌ์˜ค๋”์˜ ๊ด€๊ณ„์—๋Œ€ํ•ด์„œ๋Š” ์ƒ๊ฐํ•ด๋ณธ์ ์ด ์—†์—ˆ๋Š”๋ฐ ์‹ ๊ธฐํ•˜๊ณ  ์–ด๋ ค์šด ๋ฌธ์ œ์˜€๋‹ค

๋ฐ˜์‘ํ˜•