๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 17299_์˜ค๋“ฑํฐ์ˆ˜

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

Gold III

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

< ์˜ค๋“ฑํฐ์ˆ˜ >

 

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

 

17298 ์˜คํฐ์ˆ˜ ๋ฌธ์ œ์—์„œ ์ˆ˜์—ด์— ๋“ฑ์žฅํ•œ ํšŸ์ˆ˜๋งŒ ์ถ”๊ฐ€๋กœ ๊ตฌํ•˜๋‹ˆ ๋ฌธ์ œ๋ฅผ ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.

 

https://melody-coding.tistory.com/324

 

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

Gold IV๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/17298) ๋ฌธ์ œ ํ’€์ด & ์ƒ๊ฐ ์ฒ˜์Œ์—๋Š” ์ด์ค‘ ํฌ๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ ๊ตฌํ˜„ํ–ˆ๋”๋‹ˆ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค. stack์„ ์‚ฌ์šฉํ•˜์—ฌ ์‹œ๊ฐ„์ดˆ๊ณผ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.ํ˜„์žฌ ๊ฐ’๊ณผ ๋‹ค

melody-coding.tistory.com

 

 

 

 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 _17299_ { // ์˜ค๋“ฑํฐ์ˆ˜

	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());
		int arr[] = new int[n];
		int result[] = new int[n];
		int f[] = new int[1000001];

		st = new StringTokenizer(bf.readLine());
		for (int i = 0; i < n; i++) {
			int num = Integer.parseInt(st.nextToken());
			arr[i] = num;
			f[num] += 1;
			result[i] = -1;
		}

		Stack<Integer> stack = new Stack<>();
		for (int i = 0; i < n - 1; i++) {
			if (f[arr[i]] < f[arr[i + 1]]) {
				result[i] = arr[i + 1];
				while (!stack.isEmpty()) {
					if (f[arr[stack.peek()]] < f[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: ์˜ค๋“ฑํฐ์ˆ˜ ์ €์žฅ

  f : ์ˆ˜์—ด์—์„œ ๋“ฑ์žฅํ•œ ํšŸ์ˆ˜ ์ €์žฅ

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

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