성장, 그 아름다운 향연

https://www.acmicpc.net/problem/14769

 

14769번: Stacking Cups

The first line of the input file contains an integer N, the number of cups (1 ≤ N ≤ 20). Next N lines will contain two tokens each, either as “color radius” or “diameter color”. The radius of a cup R will be a positive integer less than 1000. T

www.acmicpc.net

 

문제

You are programming a cup stacking module for your robot. This robot is equiped with several sensors that can accurately determine the radius and color of a cup. The problem is that there is a glitch in the robot’s core routine that processess sensor inputs so the radius is doubled, if the result of the color sensor arrives to the routine after the radius.

For instance, for a red cup with a radius of 5 units, your module will receive either “red 5” or “10 red” message.

Given a list of messages from the core routine, each describing a different cup, can you put the cups in order of the smallest to the largest?

입력

The first line of the input file contains an integer N, the number of cups (1 ≤ N ≤ 20). Next N lines will contain two tokens each, either as “color radius” or “diameter color”. The radius of a cup R will be a positive integer less than 1000. The color of a cup C will be a non-empty string of lower case English letters of length at most 20. All cups will be different in both size and color.

출력

Output colors of cups, one color per line, in order of increasing radius.

예제 입력

3
red 10
10 blue
green 7

예제 출력

blue
green
red

 


 

문제의 핵심을 요약하면 다음과 같다.

 

n개의 컵이 주어지면서 (색상, 숫자) 이면 숫자는 반지름을 나타내고 (숫자,색상)이면 숫자가 반지름에 2배인 지름이 된다. 이 때, 반지름의 오름차순으로 정렬한 색상을 출력해야 한다.

 

 

이 문제를 접하면 다음과 같은 문제 사항을 마주하게 된다.

 

"엥? hashmap을 이용하는 건 알겠는데 hashmap은 <String, Int> 처럼 타입이 정해진 상태에서 어떻게 입력마다 알맞게 값을 넣을 수 있지?"

 

라는 고민에 빠져들게 된다.

이를 해결하기 위해서 입력값을 any로 자료형을 변경해주고, is 명령어를 통해 String인지 Int인지를 판별해서 hashMap에 적절히 넣으려 했으나 아예 조건을 통과하지도 못했다.

 

 

 

이런 저런 시도를 하던 중에 key 값의 첫 번째 문자가 숫자인지, 알파벳인지 구별해주면 입력값에 따라 넣어주면 되지 않을까 생각했다.

 

그래서 다음과 같은 로직을 구현했다.

 

val (a, b) = readLine().split(" ")
        if (a[0] in '0'..'9') {
            map[b] = (a.toInt() / 2).toString()
        } else {
            map[a] = b
        }

 

 

 

첫 번째 입력값 중에서 왼쪽값(a)의 첫번째[0]가 '0' ~ '9' 사이라면 숫자라는 뜻이니까,
key에는 b 값을, value에는 a 값에서 2를 나눈(문제에서 2배라 제시했으므로) 값을 넣었더니 해결할 수 있었다.

 

 

 

전체 코드는 다음과 같다.

 

fun main() = with(System.`in`.bufferedReader()) {
    val n = readLine().toInt()
    val map = hashMapOf<String, String>()
    repeat(n) {
        val (a, b) = readLine().split(" ")
        if (a[0] in '0'..'9') {
            map[b] = (a.toInt() / 2).toString()
        } else {
            map[a] = b
        }
    }
    map.toList().sortedBy { it.second.toInt() }.forEach {
        println(it.first)
    }
}

 

profile

성장, 그 아름다운 향연

@dev_minoflower

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

profile on loading

Loading...