Baekjoon - 7662

Tadap·2023년 10월 14일
0

Baekjoon

목록 보기
53/94

문제

Solved.ac Class3++

TreeMap

Key, Value 구조로 Comaprator에 따라 정렬해준다.
중복 Key를 허용하지 않는다.

1, 2차 시도

PriorityQueue 2개를 배치해서 시도.
시간초과로 실패

3차 시도

TreeMap 사용

public class Main {
	private static final String D = "D";
	private static final String I = "I";
	private static final String EMPTY = "EMPTY";
	public static void main(String[] args) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();

		int T = Integer.parseInt(br.readLine());

		for (int i = 0; i < T; i++) {
			int size = Integer.parseInt(br.readLine());
			TreeMap<Integer, Integer> treeMap = new TreeMap<>();

			for (int j = 0; j < size; j++) {
				String[] data = br.readLine().split(" ");
				int intData = Integer.parseInt(data[1]);
				switch (data[0]) {
					case D:
						int temp;
						if (treeMap.isEmpty()) {
							break;
						}
						if (intData == 1) {
							temp = treeMap.lastKey();
						} else {
							temp = treeMap.firstKey();
						}
						if (treeMap.put(temp, treeMap.get(temp) - 1) == 1) {
							treeMap.remove(temp);
						}
						break;
					case I:
						treeMap.put(intData, treeMap.getOrDefault(intData, 0) + 1);
				}
			}

			if (treeMap.isEmpty()) {
				sb.append(EMPTY).append("\n");
			} else {
				sb.append(treeMap.lastKey()).append(" ").append(treeMap.firstKey()).append("\n");
			}
		}
		System.out.println(sb);
	}
}

TreeMap의 경우 put을 하면 이전 값을 리턴한다.
처음 put이면 null을 아니면 이전값을

성공

ToKotlin

fun main() {
    val p = Problem7662ToKotlin()
    val T = readln().toInt()
    val sb = StringBuilder()
    for (i in 0..<T) {
        sb.append(p.solve())
    }
    print(sb)
}

class Problem7662ToKotlin {

    fun solve():String {
        val size = readln().toInt()
        val sortedMap = sortedMapOf<Int, Int>()

        for (i in 0..<size) {
            val data = readln().split(" ")
            val intData = data[1].toInt()

            if (data[0] == "I") {
                sortedMap.put(intData, sortedMap.getOrDefault(intData, 0) + 1)
            } else {
                if (sortedMap.isEmpty()) {
                    continue
                }
                var temp: Int
                if (intData == 1) {
                    temp = sortedMap.lastKey()
                } else {
                    temp = sortedMap.firstKey()
                }
                if (sortedMap.put(temp, sortedMap.get(temp)?.minus(1)) == 1) {
                    sortedMap.remove(temp)
                }
            }
        }

        if (sortedMap.isEmpty()) {
            return "EMPTY\n"
        }

        val sb = StringBuilder()

        sb.append(sortedMap.lastKey()).append(" ").append(sortedMap.firstKey()).append("\n")

        return sb.toString()

    }
}

0개의 댓글