Unit Conversion II
There are n unit types, numbered 0 to n - 1. Each conversion [source, target, factor] means one unit of source equals factor units of target. The conversions form a tree rooted at unit 0, and every factor is at least 1.
Each query [a, b] asks how many units of b equal one unit of a, modulo 1_000_000_007. Return one answer per query.
queryConversions(3, [[0, 1, 2], [1, 2, 3]], [[0, 2], [2, 0]]) -> [6, 166666668]
One unit of 0 is 6 units of 2, so one unit of 2 is 1/6 of a unit of 0 — which is 166666668 modulo 1_000_000_007. Products can exceed 2^53 before the modulo — in JavaScript, do the arithmetic in BigInt (the harness converts your answers back to numbers).
Hints
Hint 1
First compute ans[i] = units of i per one unit of 0 with one traversal from the root: ans[child] = ans[parent] × factor (mod p).
Hint 2
One unit of a is ans[b] / ans[a] units of b — but you cannot divide under a modulus. Because p is prime, Fermat gives the inverse: ans[a]^(p−2) mod p. Multiply instead of dividing.