๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 25381_ABBC

๋ฟŒ์•ผ._. 2023. 8. 30. 14:14

Gold IV

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

< ABBC >

 

๋ฌธ์ œ ํ’€์ด 

 

A -> B , B -> C๋ฅผ ์ง€์šฐ๊ธฐ ์œ„ํ•ด์„œ๋Š” ์–ด๋””์— ์œ„์น˜ํ•œ B๋ฅผ ์ง€์šฐ๋Š”๊ฐ€๊ฐ€ ์ค‘์š”ํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹ค.

 

A๋ฅผ ๋’ค์—์„œ๋ถ€ํ„ฐ ์ง€์šธ ๋•Œ B ๋˜ํ•œ ๋’ค์—์„œ๋ถ€ํ„ฐ ์ง€์šด๋‹ค.

B๋ฅผ ์•ž์—์„œ๋ถ€ํ„ฐ ์ง€์šธ ๋•Œ C ๋˜ํ•œ ์•ž์—์„œ๋ถ€ํ„ฐ ์ง€์šด๋‹ค.

 

์ด ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ–ˆ๋‹ค.

 

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;

public class _25381_ { // ABBC

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

		String str = bf.readLine();

		PriorityQueue<Integer> aQueue = new PriorityQueue<>(Collections.reverseOrder());
		Deque<Integer> bQueue = new ArrayDeque<>();
		Queue<Integer> cQueue = new LinkedList<>();

		int result = 0;

		for (int i = 0; i < str.length(); i++) {
			char x = str.charAt(i);
			if (x == 'A') {
				aQueue.add(i);
			} else if (x == 'B') {
				bQueue.add(i);
			} else if (x == 'C') {
				cQueue.add(i);
			}
		}

		while (!aQueue.isEmpty()) {
			int num = aQueue.poll();
			if (!bQueue.isEmpty() && num < bQueue.peekLast()) {
				result += 1;
				bQueue.pollLast();
			}
		}

		while (!bQueue.isEmpty()) {
			int num = bQueue.pollFirst();
			while(!cQueue.isEmpty() && num > cQueue.peek()) {
				cQueue.poll();
			}
			if(!cQueue.isEmpty() && num < cQueue.peek()) {
				result+=1;
				cQueue.poll();
			}
		}

		System.out.println(result);
	}
}

 

Main

๋ณ€์ˆ˜)
str : ๋ฌธ์ž์—ด
aQueue : PriorityQueue <Integer>
bQueue : Deque <Integer> 
cQueue : Queue <Integer>
result : ์‹œํ–‰ํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ํšŸ์ˆ˜

 

- ๋ฌธ์ž์—ด(str) ์ž…๋ ฅ

- ๋ฌธ์ž์—ด ํƒ์ƒ‰ํ•˜๋ฉด์„œ A, B, C์˜ ๊ฐ๊ฐ index๋ฅผ ์ €์žฅ

- ๋ฌธ์ž์—ด ๋’ค์— ์žˆ๋Š” A๋ถ€ํ„ฐ ์ œ๊ฑฐํ•˜๋ฉฐ B ๋˜ํ•œ ๋’ค์— ์žˆ๋Š” B๋ถ€ํ„ฐ ์ œ๊ฑฐ

: A์˜ index๋ณด๋‹ค B์˜ index๊ฐ€ ์ปค์•ผ result+1 ํ›„ ์ œ๊ฑฐ ๊ฐ€๋Šฅ

- ๋ฌธ์ž์—ด ์•ž์— ์žˆ๋Š” B๋ถ€ํ„ฐ ์ œ๊ฑฐํ•˜๋ฉฐ C ๋˜ํ•œ ์•ž์— ์žˆ๋Š” C๋ถ€ํ„ฐ ์ œ๊ฑฐ

: B์˜ index๋ณด๋‹ค C์˜ index๊ฐ€ ์ž‘๋‹ค๋ฉด ๊ณ„์†ํ•ด์„œ ์ œ๊ฑฐํ•  ์ˆ˜ ์—†์œผ๋ฏ€๋กœ C์˜ index๊ฐ€ ๋” ์ปค์งˆ ๋•Œ๊นŒ์ง€ ์ œ๊ฑฐ

: B์˜ index๊ฐ€ C์˜ index๋ณด๋‹ค ์ž‘๋‹ค๋ฉด result+1 ํ›„ C ์ œ๊ฑฐ

- ์‹œํ–‰ํ•  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ํšŸ์ˆ˜(result) ์ถœ๋ ฅ