hades

[Baekjoon] 5639๋ฒˆ: ์ด์ง„ ๊ฒ€์ƒ‰ ํŠธ๋ฆฌ ๋ณธ๋ฌธ

๐Ÿ‘Š PS/Algorithm

[Baekjoon] 5639๋ฒˆ: ์ด์ง„ ๊ฒ€์ƒ‰ ํŠธ๋ฆฌ

hades1 2024. 9. 6. 13:10

๐Ÿฅ… ๋ฌธ์ œ

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

 

๐Ÿ” ์„ค๊ณ„

์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ 50 30 24 5 28 45 98 52 60 ์—์„œ ๋ฃจํŠธ, L, R์„ ๊ตฌ๋ถ„ํ•˜๋ฉด, 50 30 24 5 28 45 98 52 60 ์ด๋‹ค.

L, R ์„œ๋ธŒํŠธ๋ฆฌ ๊ฐ๊ฐ์˜ ์„œ๋ธŒํŠธ๋ฆฌ๋ฅผ ๊ตฌํ•ด๋„ ๋ฃจํŠธ๋Š” ์ฒซ ๋ฒˆ์งธ, L์€ ๋‘ ๋ฒˆ๋ถ€ํ„ฐ ๋ฃจํŠธ๋ณด๋‹ค ์ž‘์€ ์ˆ˜๊นŒ์ง€, R์€ ๋ฃจํŠธ๋ณด๋‹ค ํฐ ์ˆ˜๋ถ€ํ„ฐ ๋๊นŒ์ง€๋ผ๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

 

์„œ๋ธŒ ํŠธ๋ฆฌ์— ํ•ด๋‹นํ•˜๋Š” ์ธ๋ฑ์Šค์˜ ๋ฒ”์œ„๋ฅผ ์žฌ๊ท€๋กœ ๋งŒ๋“ค์–ด์„œ LRV๋ฅผ ์ง„ํ–‰ํ•˜๋ฉด ๋œ๋‹ค.

 

์ฃผ์˜ํ•ด์•ผํ•  ์ ์€ ๊ฐœ์ˆ˜๊ฐ€ ์ •ํ•ด์ ธ ์žˆ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์—, while์„ ์ด์šฉํ•˜์—ฌ ๋ฒกํ„ฐ์— ์ž…๋ ฅ๊ฐ’์„ ์ง€์ •ํ–ˆ๋Š”๋ฐ, ์ด๋Ÿด ๊ฒฝ์šฐ ์ตœ์ข… ์ธ๋ฑ์Šค๋Š” ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค๋ณด๋‹ค ํ•˜๋‚˜ ๋” ๋งŽ์€ ์ด ๊ฐœ์ˆ˜์ด๋‹ค. ๋”ฐ๋ผ์„œ ๋ฒ”์œ„๋ฅผ ์ง€์ •ํ•  ๋•Œ, end๋Š” ์‚ฌ์šฉ๋˜์ง€ ์•Š๋Š”๋‹ค๋Š” ๊ฒƒ์— ์œ ์˜ํ•ด์•ผ ํ•œ๋‹ค.

 

๐Ÿ‘Š ํ’€์ด

#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

vector<int> tree(10000);

void postOrder(int start, int end) {
	if (start >= end) {
		return;
	}
	if (start == end - 1) {
		cout << tree[start] << "\n";
		return;
	}
	int root = tree[start];
	int branch_idx = start + 1;
	while (branch_idx < end) {
		if (root < tree[branch_idx]) {
			break;
		}
		branch_idx += 1;
	}
	postOrder(start + 1, branch_idx);
	postOrder(branch_idx, end);
	cout << tree[start] << "\n";
}

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);	
	
	int num;
	int cur_idx = 0;

	while (cin >> num) {
		tree[cur_idx++] = num;
	}

	postOrder(0, cur_idx);

	return 0;
}