Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the distance array with infinity.
DSA C++
vector<int> dist(V, [1]);Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 instead of INT_MAX causes incorrect distance initialization.
Using negative values for initial distances.
✗ Incorrect
We initialize distances to INT_MAX to represent infinity before relaxation.
2fill in blank
mediumComplete the code to relax edges inside the main loop.
DSA C++
if (dist[u] != INT_MAX && dist[u] + weight < dist[[1]]) { dist[[1]] = dist[u] + weight; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using the source vertex u instead of destination v.
Using weight or dist as index.
✗ Incorrect
We update the distance of vertex v if a shorter path is found through u.
3fill in blank
hardFix the error in the negative cycle detection condition.
DSA C++
for (auto edge : edges) { int u = edge.src, v = edge.dest, weight = edge.weight; if (dist[u] != INT_MAX && dist[u] + weight [1] dist[v]) { return true; // Negative cycle detected } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using > or >= instead of < causes wrong detection.
Using == does not detect negative cycles.
✗ Incorrect
If we can still relax an edge, it means a negative cycle exists, so we check if dist[u] + weight < dist[v].
4fill in blank
hardFill both blanks to complete the main relaxation loop of Bellman-Ford.
DSA C++
for (int i = 1; i <= [1] - 1; i++) { for (auto edge : edges) { int u = edge.src, v = edge.dest, weight = edge.weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[[2]]) { dist[v] = dist[u] + weight; } } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using V instead of V-1 for loop count.
Using u instead of v in distance update.
✗ Incorrect
The outer loop runs V-1 times, and relaxation updates dist[v] if shorter path found.
5fill in blank
hardFill all three blanks to complete the Bellman-Ford function header and initialization.
DSA C++
bool bellmanFord(int [1], vector<Edge>& [2], int [3]) { vector<int> dist(V, INT_MAX); dist[src] = 0; // Relax edges // ... }
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing parameter order or names.
Using weight instead of src for source vertex.
✗ Incorrect
Function takes number of vertices V, list of edges, and source vertex src.
