Problem
There are n
types of units indexed from 0
to n - 1
.
You are given a 2D integer array conversions
of length n - 1
, where conversions[i] = [sourceUniti, targetUniti, conversionFactori]
. This indicates that a single unit of type sourceUniti
is equivalent to conversionFactori
units of type targetUniti
.
You are also given a 2D integer array queries
of length q
, where queries[i] = [unitAi, unitBi]
.
Return an array answer
of length q
where answer[i]
is the number of units of type unitBi
equivalent to 1 unit of type unitAi
, and can be represented as p/q
where p
and q
are coprime. Return each answer[i]
as pq-1
modulo 109 + 7
, where q-1
represents the multiplicative inverse of q
modulo 10^9 + 7
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
2 <= n <= 10^5
conversions.length == n - 1
0 <= sourceUniti, targetUniti < n
1 <= conversionFactori <= 10^9
1 <= q <= 10^5
queries.length == q
0 <= unitAi, unitBi < n
- It is guaranteed that unit 0 can be uniquely converted into any other unit through a combination of forward or backward conversions.
Solution
Method 1 – DFS/BFS for Conversion Ratios
Intuition
We can model the conversions as a bidirectional weighted graph. For each query, we can find the conversion ratio between two units by traversing the graph. To answer queries efficiently, we can precompute the conversion ratio from unit 0 to every other unit using DFS or BFS, then answer each query in O(1) using these ratios.
Approach
- Build a graph where each edge represents a conversion (and its inverse).
- Use DFS/BFS to compute the ratio from unit 0 to every other unit, storing as numerator/denominator (in reduced form).
- For each query, compute the ratio between unitAi and unitBi as (ratio[unitAi] / ratio[unitBi]).
- Return the result as p * q^-1 mod 1e9+7, where q^-1 is the modular inverse.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + q)
— Build graph and DFS is O(n), each query is O(1). - 🧺 Space complexity:
O(n)
— For graph and ratios.