목차

칵테일

ps
링크acmicpc.net/…
출처BOJ
문제 번호1033
문제명칵테일
레벨골드 2
분류

수학

시간복잡도O(nlogm)
인풋사이즈n<=10, m<=9
사용한 언어Python 3.11
제출기록39512KB / 120ms
최고기록33ms
해결날짜2024/10/25

풀이

코드

"""Solution code for "BOJ 1033. 칵테일".

- Problem link: https://www.acmicpc.net/problem/1033
- Solution link: http://www.teferi.net/ps/problems/boj/1033

Tags: [math]
"""

import math
import fractions


def main():
    N = int(input())
    wtree = [{} for _ in range(N)]
    for _ in range(N - 1):
        a, b, p, q = [int(x) for x in input().split()]
        wtree[a][b] = fractions.Fraction(q, p)
        wtree[b][a] = fractions.Fraction(p, q)

    ratio = [fractions.Fraction(1) for _ in range(N)]
    root = 0
    stack = [root]
    visited = [False] * N
    visited[root] = True
    while stack:
        u = stack.pop()
        for v, w in wtree[u].items():
            if visited[v]:
                continue
            visited[v] = True
            ratio[v] = ratio[u] * w
            stack.append(v)
    lcm = math.lcm(*(ratio_u.denominator for ratio_u in ratio))
    answer = [ratio_u * lcm for ratio_u in ratio]

    print(*answer)


if __name__ == '__main__':
    main()