[백준 - 1004] 어린 왕자

kldaji·2022년 2월 25일
1

백준

목록 보기
14/76

문제링크

첫번째 시도 (실패)

import kotlin.math.pow
import kotlin.math.sqrt

data class Circle(val x: Int, val y: Int, val radius: Int)

fun main() {
    val bufferedReader = System.`in`.bufferedReader()
    val bufferedWriter = System.out.bufferedWriter()

    val t = bufferedReader.readLine().toInt()
    repeat(t) {
        val (x1, y1, x2, y2) = bufferedReader.readLine().split(" ").map { it.toInt() }
        val n = bufferedReader.readLine().toInt()
        val circles = mutableListOf<Circle>()

        repeat(n) {
            val (x, y, radius) = bufferedReader.readLine().split(" ").map { it.toInt() }
            circles.add(Circle(x, y, radius))
        }

        var answer = 0
        for (circle in circles) {
            if (isInTheCircle(x1, y1, circle)) answer++
            if (isInTheCircle(x2, y2, circle)) answer++
        }
        bufferedWriter.write("$answer\n")
    }

    bufferedReader.close()
    bufferedWriter.close()
}

fun isInTheCircle(x: Int, y: Int, circle: Circle): Boolean {
    val distance = getDistanceWithoutSqrt(x, y, circle)
    return distance < circle.radius * circle.radius
}

fun getDistanceWithoutSqrt(x: Int, y: Int, circle: Circle): Int {
    return (x - circle.x) * (x - circle.x) + (y - circle.y) * (y - circle.y)
}

두번째 시도 (성공)

  • 둘 다 원에 있는 경우는 제외시켜야 합니다.
  • 즉, 둘 중에 하나만 원 안에 있는 경우를 증가시켜야 합니다.
data class Circle(val x: Int, val y: Int, val radius: Int)

fun main() {
    val bufferedReader = System.`in`.bufferedReader()
    val bufferedWriter = System.out.bufferedWriter()

    val t = bufferedReader.readLine().toInt()
    repeat(t) {
        val (x1, y1, x2, y2) = bufferedReader.readLine().split(" ").map { it.toInt() }
        val n = bufferedReader.readLine().toInt()
        val circles = mutableListOf<Circle>()

        repeat(n) {
            val (x, y, radius) = bufferedReader.readLine().split(" ").map { it.toInt() }
            circles.add(Circle(x, y, radius))
        }

        var answer = 0
        for (circle in circles) {
            // 둘 중에 하나만 원에 있는 경우
            if (isInTheCircle(x1, y1, circle) != isInTheCircle(x2, y2, circle)) answer++
        }
        bufferedWriter.write("$answer\n")
    }

    bufferedReader.close()
    bufferedWriter.close()
}

fun isInTheCircle(x: Int, y: Int, circle: Circle): Boolean {
    val distance = getDistanceWithoutSqrt(x, y, circle)
    return distance < circle.radius * circle.radius
}

fun getDistanceWithoutSqrt(x: Int, y: Int, circle: Circle): Int {
    return (x - circle.x) * (x - circle.x) + (y - circle.y) * (y - circle.y)
}

주석 없는 코드를 만들기 위해 노력하는 개발자입니다.

혹시라도 의도가 분명하지 않아보이는 (이해가 되지 않는) 코드가 있으시다면 편하게 답변 달아주시면 정말 감사하겠습니다.

profile
다양한 관점에서 다양한 방법으로 문제 해결을 지향하는 안드로이드 개발자 입니다.

0개의 댓글