๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 17298_์˜คํฐ์ˆ˜

๋ฟŒ์•ผ._. 2023. 6. 28. 13:21

Gold IV

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/17298)

< ์˜คํฐ์ˆ˜ >

 

๋ฌธ์ œ ํ’€์ด & ์ƒ๊ฐ

 

์ฒ˜์Œ์—๋Š” ์ด์ค‘ ํฌ๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ ๊ตฌํ˜„ํ–ˆ๋”๋‹ˆ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.

 

stack์„ ์‚ฌ์šฉํ•˜์—ฌ ์‹œ๊ฐ„์ดˆ๊ณผ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.

ํ˜„์žฌ ๊ฐ’๊ณผ ๋‹ค์Œ ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ ๋‹ค์Œ ๊ฐ’์ด ํฌ๋‹ค๋ฉด ์˜คํฐ์ˆ˜ ์ด๋ฏ€๋กœ ๋‹ต์„ ์ถœ๋ ฅํ•˜๊ณ  ์˜คํฐ์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด stack์— ๋„ฃ์–ด ํฐ ๊ฐ’์ด ์˜ฌ ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆฌ๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค.

 

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Stack;
import java.util.StringTokenizer;

public class _17298_ { // ์˜คํฐ์ˆ˜

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		StringTokenizer st;

		int n = Integer.parseInt(bf.readLine());
		st = new StringTokenizer(bf.readLine());

		Stack<Integer> stack = new Stack<>();
		int arr[] = new int[n];
		int result[] = new int[n];
		for (int i = 0; i < n; i++) {
			int num = Integer.parseInt(st.nextToken());
			arr[i] = num;
			result[i] = -1;
		}

		for (int i = 0; i < n - 1; i++) {
			if (arr[i] < arr[i + 1]) {
				result[i] = arr[i + 1];
				if (!stack.isEmpty()) {
					while (!stack.isEmpty()) {
						if (arr[stack.peek()] < arr[i + 1]) {
							int num = stack.pop();
							result[num] = arr[i + 1];
						}else {
							break;
						}
					}
				}

			} else {
				stack.add(i);
			}
		}
		for (int i = 0; i < n; i++) {
			bw.write(result[i] + " ");
		}
		bw.flush();
	}
}

 

Main

- ์ˆ˜์—ด A์˜ ํฌ๊ธฐ (n) ์ž…๋ ฅ

- arr : ์ˆ˜์—ด ์ €์žฅ

  result: ์˜คํฐ์ˆ˜ ์ €์žฅ

- ์ˆ˜์—ด์„ ํƒ์ƒ‰ํ•˜๋ฉฐ ํ˜„์žฌ ๊ฐ’๊ณผ ๋‹ค์Œ ๊ฐ’์„ ๋น„๊ต -> ๋‹ค์Œ ๊ฐ’์ด ํ˜„์žฌ ๊ฐ’ ๋ณด๋‹ค ํฌ๋‹ค๋ฉด ์˜คํฐ์ˆ˜ ์ด๋ฏ€๋กœ result ๋ฐฐ์—ด์— ์ €์žฅ, stack์— ๊ฐ’์ด ์žˆ๋Š”์ง€ ํ™•์ธ ํ›„ stack์— ์žˆ๋Š” ๊ฐ’์ด ๋‹ค์Œ ๊ฐ’๋ณด๋‹ค ์ž‘๋‹ค๋ฉด stack์— ์žˆ๋Š” ๊ฐ’์˜ ์˜คํฐ์ˆ˜๋ฅผ ์ฐพ์€ ๊ฒƒ์ด๋ฏ€๋กœ ์˜คํฐ์ˆ˜ ์ €์žฅ  But ์˜คํฐ์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด ์˜คํฐ์ˆ˜๋ฅผ ์ฐพ๊ธฐ ์œ„ํ•ด stack์— ๊ฐ’์„ ์ €์žฅ

- result ๋ฐฐ์—ด ์ถœ๋ ฅ