๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 17952_๊ณผ์ œ๋Š” ๋๋‚˜์ง€ ์•Š์•„!

๋ฟŒ์•ผ._. 2023. 8. 24. 21:54

Silver III

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

< ๊ณผ์ œ๋Š” ๋๋‚˜์ง€ ์•Š์•„! >

 

๋ฌธ์ œ ํ’€์ด 

 

Stack์„ ์‚ฌ์šฉํ•ด์„œ 0์ด ์ž…๋ ฅ๋  ๋•Œ๋Š” stack์—์„œ ๊ฐ’์„ popํ•ด์™€ ์‹œ๊ฐ„์„ -1 ์‹œ์ผœ ๋‹ค์‹œ stack์— ๋„ฃ์–ด์ฃผ๋ฉฐ ๋งŒ์•ฝ ์‹œ๊ฐ„์ด 1์ด๋ผ๋ฉด ๊ณผ์ œ๋ฅผ ๋๋‚ผ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ์ ์ˆ˜๋ฅผ ์ดํ•ฉ์— ๋”ํ•ด์ค€๋‹ค. ๋งŒ์•ฝ 1์ด ์ž…๋ ฅ๋  ๋•Œ๋Š” stack์— ๊ฐ’์„ ๋„ฃ์–ด์ค€๋‹ค.

 

 

 my solution (Java)

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

public class _17952_ { // ๊ณผ์ œ๋Š” ๋๋‚˜์ง€ ์•Š์•„!

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

		int n = Integer.parseInt(bf.readLine());

		Stack<int[]> stack = new Stack<>();
		int answer = 0;

		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(bf.readLine());
			int num = Integer.parseInt(st.nextToken());
			if (num == 0) {
				if (!stack.isEmpty()) {
					int temp[] = stack.pop();
					if (temp[1] == 1)
						answer += temp[0];
					else
						stack.add(new int[] { temp[0], temp[1] - 1 });
				}
			} else {
				int a = Integer.parseInt(st.nextToken());
				int t = Integer.parseInt(st.nextToken());

				if (t == 1)
					answer += a;
				else
					stack.add(new int[] { a, t - 1 });
			}
		}
		System.out.println(answer);
	}
}

 

Main

๋ณ€์ˆ˜)
n : ์ฃผ์–ด์ง„ ์‹œ๊ฐ„
stack : Stack<[๊ณผ์ œ ์ ์ˆ˜, ๋‚จ์€ ์‹œ๊ฐ„]> 
answer : ๊ณผ์ œ ์ ์ˆ˜ ์ดํ•ฉ
num: 0 or 1

 

- ์ฃผ์–ด์ง„ ์‹œ๊ฐ„(n) ์ž…๋ ฅ

- ์ฃผ์–ด์ง„ ์‹œ๊ฐ„(n)๋งŒํผ ๊ณผ์ œ ์ž…๋ ฅ

: 0์ด๋ฉด ๊ณผ์ œ๊ฐ€ ์ฃผ์–ด์ง€์ง€ ์•Š์œผ๋ฏ€๋กœ ๊ณผ์ œ ์ด์–ด์„œ ์ง„ํ–‰ -> ๋งŒ์•ฝ 1๋ถ„ ๋‚จ์•˜์œผ๋ฉด ๊ณผ์ œ๊ฐ€ ๋๋‚˜๋ฏ€๋กœ ์ดํ•ฉ(answer)์— ์ ์ˆ˜ ์ถ”๊ฐ€, 1๋ถ„๋ณด๋‹ค ๋งŽ์ด ๋‚จ์•˜๋‹ค๋ฉด ๋‚จ์€ ์‹œ๊ฐ„-1 ํ•ด์„œ stack์— ์ถ”๊ฐ€

: 1์ด๋ฉด ๊ณผ์ œ๊ฐ€ ์ฃผ์–ด์ง€๋ฉฐ ๊ณผ์ œ๋ฅผ ๋ฐ›์ž๋งˆ์ž ์‹œ์ž‘ํ•˜๋ฏ€๋กœ ์‹œ๊ฐ„-1 ํ•ด์„œ stack์— ์ถ”๊ฐ€ (์ฃผ์–ด์ง€๋Š” ๊ณผ์ œ๊ฐ€ 1๋ถ„์ด๋ผ๋ฉด ๋ฐ”๋กœ ์ข…๋ฃŒ๋˜๋ฏ€๋กœ ์ดํ•ฉ(answer)์— ์ถ”๊ฐ€)