Approach
Breadth-first search
For Number of Ways to Assign Edge Weights I, 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
- 44 lines of C++ from the credited upstream file 3558.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 int assignEdgeWeights(vector<vector<int>>& edges) {4 const int n = edges.size() + 1;5 vector<vector<int>> graph(n + 1);6 7 for (const vector<int>& edge : edges) {8 const int u = edge[0];9 const int v = edge[1];10 graph[u].push_back(v);11 graph[v].push_back(u);12 }13 14 queue<int> q{{1}};15 vector<bool> seen(n + 1);16 seen[1] = true;17 int step = 0;18 19 for (step = 0; !q.empty(); ++step)20 for (int sz = q.size(); sz > 0; --sz) {21 const int u = q.front();22 q.pop();23 for (const int v : graph[u])24 if (!seen[v]) {25 q.push(v);26 seen[v] = true;27 }28 }29 30 return step > 0 ? modPow(2, step - 2) : 0;31 }32 33 private:34 static constexpr int kMod = 1'000'000'007;35 36 long modPow(long x, long n) {37 if (n == 0)38 return 1;39 if (n % 2 == 1)40 return x * modPow(x % kMod, (n - 1)) % kMod;41 return modPow(x * x % kMod, (n / 2)) % kMod;42 }43};44