A telecom crew is calibrating a chain of signal relays scattered across a mountain range. The relays are numbered 0 to n - 1, and relay 0 is the reference tower whose broadcast frequency defines the baseline. The relays are wired into a tree: exactly n - 1 physical links connect them, so every relay is reachable from the reference tower through exactly one path. Each link joins two relays u and v and carries a calibration multiplier: whenever a signal travels from u to v along that link, its frequency is multiplied by p and divided by q. Travelling the other way, from v to u, does the opposite (multiplied by q, divided by p). For every relay, report the exact ratio between its calibrated frequency and the frequency of relay 0, written as a fraction in lowest terms. Because the tree can be deep and the multipliers can compound across many links, the numerator and denominator of an answer may be far too large to fit in a 64-bit integer — you must compute and print them exactly, using arbitrary-precision arithmetic, never floating point and never a modulus.
Line 1: a single integer n — the number of relays.
Each of the next n - 1 lines contains four integers u v p q — a link between relay u and relay v (0-indexed, u != v). Travelling from u to v along that link multiplies the frequency by p and divides it by q; travelling from v to u does the opposite. The n - 1 links are guaranteed to connect all n relays into a single tree.
Print n lines. The i-th line (0-indexed) must contain two integers num den separated by a space: the numerator and denominator, in lowest terms (den > 0, gcd(num, den) = 1), of the exact ratio frequency(i) / frequency(0). For relay 0 itself this ratio is 1 1.
2 <= n <= 600 <= u, v <= n - 1, u != v1 <= p, q <= 10^9n relays.Example 1
Input
4 0 1 3 2 1 2 5 4 0 3 7 1
Expected
1 1 3 2 15 8 7 1
Explanation
Relay 1 is reached from relay 0 by the first link, so its ratio is 3/2. Relay 2 is reached from relay 1 by the second link, so its ratio is (3/2) * (5/4) = 15/8. Relay 3 is reached directly from relay 0 by the third link, so its ratio is 7/1. Relay 0's ratio to itself is always 1/1.
Example 2
Input
3 1 0 2 3 2 1 5 7
Expected
1 1 3 2 21 10
Explanation
The first link is given as `1 0 2 3`, meaning travelling from 1 to 0 multiplies by 2/3 — so travelling the other way, from 0 to 1, multiplies by 3/2, giving relay 1 the ratio 3/2. The second link is `2 1 5 7`, meaning travelling from 2 to 1 multiplies by 5/7 — so travelling from 1 to 2 multiplies by 7/5. Relay 2's ratio is therefore (3/2) * (7/5) = 21/10.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →