Tap here to switch tabs
Problem
Submissions

Problem: Unit Conversion II

Try to solve the Unit Conversion II problem.

Statement

You are given an integer nn, representing nn units numbered from 00 to n−1n - 1.

You are also given a 2D integer array conversions of length n−1n - 1, where conversions[i] = [sourceUnit_i, targetUnit_i, conversionFactor_i] indicates that 11 unit of sourceUnit_i is equal to conversionFactor_i units of targetUnit_i.

You are also given a 2D integer array queries, where queries[j] = [unitA_j, unitB_j] asks for the number of units of unitB_j that equal 11 unit of unitA_j.

Return an array of integers representing the answer to each query. Since the answer may be a fractional value or very large, compute the result modulo 109+710^9 + 7 by returning the answer multiplied by the modular multiplicative inverse modulo 109+710^9 + 7.

Note: The division AB(mod109+7)\frac{A}{B} \pmod{10^9 + 7} is calculated as (A×B−1)(mod109+7)(A \times B^{-1}) \pmod{10^9 + 7}, where B−1B^{-1} is the modular multiplicative inverse of BB modulo 109+710^9 + 7.

Constraints:

  • 2≤n≤1052 \leq n \leq 10^5

  • conversions.length =n−1= n - 1

  • 0≤0 \leq sourceUnit_i, targetUnit_i <n< n

  • 1≤1 \leq conversionFactor_i ≤109\leq 10^9

  • 1≤q≤1051 \leq q \leq 10^5

  • queries.length =q= q

  • 0≤0 \leq unitA_j, unitB_j <n< n

  • It is guaranteed that unit 00 can be uniquely converted into any other unit through a combination of forward or backward conversions.

⋮
Tap here to switch tabs
Problem
Submissions

Problem: Unit Conversion II

Try to solve the Unit Conversion II problem.

Statement

You are given an integer nn, representing nn units numbered from 00 to n−1n - 1.

You are also given a 2D integer array conversions of length n−1n - 1, where conversions[i] = [sourceUnit_i, targetUnit_i, conversionFactor_i] indicates that 11 unit of sourceUnit_i is equal to conversionFactor_i units of targetUnit_i.

You are also given a 2D integer array queries, where queries[j] = [unitA_j, unitB_j] asks for the number of units of unitB_j that equal 11 unit of unitA_j.

Return an array of integers representing the answer to each query. Since the answer may be a fractional value or very large, compute the result modulo 109+710^9 + 7 by returning the answer multiplied by the modular multiplicative inverse modulo 109+710^9 + 7.

Note: The division AB(mod109+7)\frac{A}{B} \pmod{10^9 + 7} is calculated as (A×B−1)(mod109+7)(A \times B^{-1}) \pmod{10^9 + 7}, where B−1B^{-1} is the modular multiplicative inverse of BB modulo 109+710^9 + 7.

Constraints:

  • 2≤n≤1052 \leq n \leq 10^5

  • conversions.length =n−1= n - 1

  • 0≤0 \leq sourceUnit_i, targetUnit_i <n< n

  • 1≤1 \leq conversionFactor_i ≤109\leq 10^9

  • 1≤q≤1051 \leq q \leq 10^5

  • queries.length =q= q

  • 0≤0 \leq unitA_j, unitB_j <n< n

  • It is guaranteed that unit 00 can be uniquely converted into any other unit through a combination of forward or backward conversions.