diff --git a/tgyuuAn/README.md b/tgyuuAn/README.md index 7c736130..13ba0bfe 100644 --- a/tgyuuAn/README.md +++ b/tgyuuAn/README.md @@ -86,4 +86,5 @@ | 80차시 | 2024.11.11 | 다익스트라 | 최소비용 구하기 2 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/254 | 81차시 | 2024.11.15 | 이분 탐색 | Cubeeditor | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/255 | 82차시 | 2024.11.22 | 희소 배열 | 합성함수와 쿼리 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/257 +| 83차시 | 2024.12.01 | 수학 + 구현 | 칵테일 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/259 --- diff --git "a/tgyuuAn/\354\210\230\355\225\231/\354\271\265\355\205\214\354\235\274.kt" "b/tgyuuAn/\354\210\230\355\225\231/\354\271\265\355\205\214\354\235\274.kt" new file mode 100644 index 00000000..52eb880e --- /dev/null +++ "b/tgyuuAn/\354\210\230\355\225\231/\354\271\265\355\205\214\354\235\274.kt" @@ -0,0 +1,98 @@ +fun gcd(a: Int, b: Int): Int { + var tempA = maxOf(a, b) + var tempB = minOf(a, b) + + if(tempB <= 0){ + return 0 + } + + while (tempA % tempB >= 1){ + val tempC = tempA%tempB + tempA = tempB + tempB = tempC + } + + return tempB +} + +fun main() { + val N = readln().toInt() + val ratio = IntArray(N){ 1 } + val linked = Array(N) { mutableListOf() } + + repeat(N-1){ + val info = readln().split(" ").map{ it.toInt() } + val a = info[0] + val b = info[1] + var p = info[2] + var q = info[3] + val divGcd = gcd(p, q) + p /= divGcd + q /= divGcd + + // println("$a $b $p $q") + + val aLinked = mutableSetOf(a) + val aDeq = ArrayDeque() + aDeq.addFirst(a) + while(!aDeq.isEmpty()){ + val now = aDeq.removeFirst() + + for(neighbor in linked[now]){ + if(neighbor in aLinked){ + continue + } + + aLinked.add(neighbor) + aDeq.addLast(neighbor) + } + } + + val bLinked = mutableSetOf(b) + val bDeq = ArrayDeque() + bDeq.addFirst(b) + while(!bDeq.isEmpty()){ + val now = bDeq.removeFirst() + + for(neighbor in linked[now]){ + if(neighbor in bLinked){ + continue + } + + bLinked.add(neighbor) + bDeq.addLast(neighbor) + } + } + + // println("$aLinked $bLinked") + + val tempARatio = ratio[a] + val tempBRatio = ratio[b] + + for(aNeighbor in aLinked){ + ratio[aNeighbor] *= (tempBRatio * p) + } + + for(bNeighbor in bLinked){ + ratio[bNeighbor] *= (tempARatio * q) + } + + linked[a].add(b) + linked[b].add(a) + + // println(linked.toList().toString()) + // println(ratio.toList().toString()) + // println() + } + + val allGcd = ratio.reduce(::gcd) + for(elemIdx in 0 until ratio.size){ + ratio[elemIdx] /= allGcd + } + + println(ratio.toList() + .toString() + .replace(",", "") + .replace("[", "") + .replace("]", "")) +} \ No newline at end of file