Approach
Breadth-first search
For Unit Conversion II, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 56 lines of C++ from the credited upstream file 3535.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> queryConversions(vector<vector<int>>& conversions,4 vector<vector<int>>& queries) {5 const vector<int> units = baseUnitConversions(conversions);6 vector<int> ans;7 8 for (const vector<int>& query : queries) {9 const int u = query[0];10 const int v = query[1];11 12 ans.push_back(units[v] * modPow(units[u], kMod - 2) % kMod);13 }14 15 return ans;16 }17 18 private:19 static constexpr int kMod = 1'000'000'007;20 21 22 vector<int> baseUnitConversions(vector<vector<int>>& conversions) {23 const int n = conversions.size() + 1;24 vector<int> res(n);25 res[0] = 1;26 queue<int> q{{0}};27 vector<vector<pair<int, int>>> graph(n);28 29 for (const vector<int>& conversion : conversions) {30 const int u = conversion[0];31 const int v = conversion[1];32 const int factor = conversion[2];33 graph[u].emplace_back(v, factor);34 }35 36 while (!q.empty()) {37 const int u = q.front();38 q.pop();39 for (const auto& [v, factor] : graph[u]) {40 res[v] = (static_cast<long>(res[u]) * factor) % kMod;41 q.push(v);42 }43 }44 45 return res;46 }47 48 long modPow(long x, long n) {49 if (n == 0)50 return 1;51 if (n % 2 == 1)52 return x * modPow(x % kMod, (n - 1)) % kMod;53 return modPow(x * x % kMod, (n / 2)) % kMod;54 }55};56