Payments app~25 min2s · 256 MBtarget O(n + m + q) time, O(n + m) spaceclassic twin: lc-399bfs
A payments app lets people hold reward points of n kinds, numbered 0 to n - 1. An exchange table lists some direct rates: [a, b, k] means 1 point of kind a is worth k points of kind b. A rate also works backwards, so 1 point of kind b is worth 1/k points of kind a. Rates can chain through other kinds.
Your team lead says: "For each question, give me the exact conversion, as a fraction in lowest terms, or -1 when the exchange table cannot answer it."
Write evaluate_ratios(n, rates, queries).
n is the number of kinds of points.rates[i] = [a, b, k] means 1 point of kind a is worth k points of kind b, where k is a whole number from 1 to 9.queries[j] = [c, d] asks how many points of kind d 1 point of kind c is worth."p/q" in lowest terms. Write "-1" when no chain of rates joins c and d.A kind is always worth 1 of itself, so c == d gives "1/1". The rates never contradict each other.
Input: n = 5, rates = [[0, 1, 2], [1, 2, 3]], queries = [[0, 2], [2, 0], [1, 0], [0, 3], [3, 3]]
Output: ["6/1", "1/6", "1/2", "-1", "1/1"]The search starts from kind 0 and gives each kind its value in units of kind 0. A rate [a, b, k] multiplies the value by 1/k going from a to b, and by k the other way.
| Taken from the queue | Kind reached | Value of 1 reached kind, in units of the first kind |
|---|---|---|
| kind 0 (the first kind) | - | 1/1 |
| kind 0 | kind 1 | 1/2 |
| kind 1 | kind 2 | 1/6 |
Then 1 point of kind 0 is worth 6 points of kind 2, and 1 point of kind 2 is worth 1/6 of a point of kind 0. Kind 3 is in no rate, so it cannot be compared with kind 0. Kind 3 compared with itself is "1/1".
Input: n = 3, rates = [[0, 1, 4]], queries = [[1, 0], [1, 2]]
Output: ["1/4", "-1"]The rate works backwards: 1 point of kind 1 is worth 1/4 of a point of kind 0. Kind 2 is in no rate.
Input: n = 1, rates = [], queries = [[0, 0]]
Output: ["1/1"]One kind is worth exactly 1 of itself.
1 ≤ n ≤ 100,0000 ≤ len(rates) ≤ 200,000, and every rate is [a, b, k] with 0 ≤ a, b < n, a ≠ b and 1 ≤ k ≤ 90 ≤ len(queries) ≤ 100,000, and every query is [c, d] with 0 ≤ c, d < n10^9.The answer for two kinds can be the product of many rates, which can overflow a normal 32-bit number. Keeping each kind's value as a reduced fraction, with both parts below 10^9, means the product of one numerator and one denominator stays below 10^18. That fits in a 64-bit integer, so use long in Java and long long in C++. JavaScript numbers are exact only up to 2^53, so use BigInt there.