๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 2841_์™ธ๊ณ„์ธ์˜ ๊ธฐํƒ€ ์—ฐ์ฃผ

๋ฟŒ์•ผ._. 2023. 8. 22. 09:26

Silver I

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

< ์™ธ๊ณ„์ธ์˜ ๊ธฐํƒ€ ์—ฐ์ฃผ >

 

๋ฌธ์ œ ํ’€์ด 

 

๊ธฐํƒ€ ์ค„๋งˆ๋‹ค stack์„ ๋งŒ๋“ค์–ด์„œ ๋ˆŒ๋Ÿฌ์•ผ ํ•˜๋Š” ํ”„๋ ›๋ณด๋‹ค ์ „์— ๋ˆ„๋ฅธ ํ”„๋ › ๋ฒˆํ˜ธ๊ฐ€ ํฐ์ง€ ์ž‘์€์ง€์— ๋”ฐ๋ผ ํŒ๋‹จํ•˜์—ฌ  ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ–ˆ๋‹ค.

 

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Stack;
import java.util.StringTokenizer;

public class _2841_ { // ์™ธ๊ณ„์ธ์˜ ๊ธฐํƒ€ ์—ฐ์ฃผ

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

		int n = Integer.parseInt(st.nextToken());
		int p = Integer.parseInt(st.nextToken());

		ArrayList<Stack<Integer>> arr = new ArrayList<>();
		for (int i = 0; i < 7; i++) {
			arr.add(new Stack<>());
		}

		int result = 0;
		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(bf.readLine());
			int num = Integer.parseInt(st.nextToken());
			int p_num = Integer.parseInt(st.nextToken());

			Stack<Integer> stack = arr.get(num);
			while (!stack.isEmpty() && stack.peek() > p_num) {
				stack.pop();
				result += 1;
			}
			if(!stack.isEmpty() && stack.peek()==p_num) {
				continue;
			}else {
				stack.add(p_num);
				result += 1;
			}
		}
		System.out.println(result);
	}
}

 

Main

๋ณ€์ˆ˜)
n : ๋ฉœ๋กœ๋””์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ์Œ์˜ ์ˆ˜
p : ํ”„๋ ›์˜ ์ˆ˜
arr : ArrayList <Stack <Integer>> ๊ธฐํƒ€ ์ค„๋งˆ๋‹ค stack์„ ๊ฐ€์ง„ ArrayList
result : ๋ฉœ๋กœ๋””๋ฅผ ์—ฐ์ฃผํ•˜๋Š”๋ฐ ํ•„์š”ํ•œ ์ตœ์†Œ ์†๊ฐ€๋ฝ ์›€์ง์ž„

 

- ๋ฉœ๋กœ๋””์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ์Œ์˜ ์ˆ˜(n), ํ”„๋ ›์˜ ์ˆ˜(p) ์ž…๋ ฅ

- ๋ฉœ๋กœ๋””์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ์Œ์˜ ์ˆ˜(n) ๋งŒํผ ๋ฐ˜๋ณต

: ์ค„์˜ ๋ฒˆํ˜ธ(num), ํ”„๋ ›์˜ ๋ฒˆํ˜ธ(p_num)๋ฅผ ์ž…๋ ฅ๋ฐ›์Œ

: ๊ทธ ์ค„(num)์— ํ•ด๋‹นํ•˜๋Š” stack์„ ๊ฐ€์ ธ์˜ด

: stack์˜ peek ๊ฐ’์ด ๋‹ค์Œ ํ”„๋ ›์˜ ๋ฒˆํ˜ธ(p_num) ๊ฐ’ ๋ณด๋‹ค ํฌ๋‹ค๋ฉด ์†๊ฐ€๋ฝ์„ ๋—€ ๋‹ค์Œ์— ๋ˆ„๋ฅผ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ stack.pop๊ณผ ์†๊ฐ€๋ฝ ์›€์ง์ž„(result) ์ถ”๊ฐ€

: ๋งŒ์•ฝ ๋‹ค์Œ ํ”„๋ ›์˜ ๋ฒˆํ˜ธ์™€ ํ˜„์žฌ ๋ˆ„๋ฅด๊ณ  ์žˆ๋Š” ํ”„๋ ›์˜ ๋ฒˆํ˜ธ๊ฐ€ ๊ฐ™๋‹ค๋ฉด ์›€์ง์ž„ x

: ๋‹ค์Œ ํ”„๋ ›์˜ ๋ฒˆํ˜ธ์™€ ํ˜„์žฌ ๋ˆ„๋ฅด๊ณ  ์žˆ๋Š” ํ”„๋ ›์˜ ๋ฒˆํ˜ธ๊ฐ€ ๊ฐ™์ง€ ์•Š๋‹ค๋ฉด stack์— ์ถ”๊ฐ€ ๋ฐ ์†๊ฐ€๋ฝ ์›€์ง์ž„(result) ์ถ”๊ฐ€

- ์ตœ์†Œ ์†๊ฐ€๋ฝ ์›€์ง์ž„(result) ์ถœ๋ ฅ