Complete the code to initialize the distance array with infinity.
vector<int> dist(V, [1]);We initialize distances with INT_MAX to represent infinity before relaxation.
Complete the code to relax edges in the topological order loop.
for (auto it : adj[u]) { int v = it.first; int weight = it.second; if (dist[u] != INT_MAX && dist[u] + weight [1] dist[v]) { dist[v] = dist[u] + weight; } }
We update dist[v] only if the new path is shorter, so we check if dist[u] + weight < dist[v].
Fix the error in the topological sort DFS function to mark nodes as visited.
void topoSort(int node, vector<bool> &visited, stack<int> &st, vector<pair<int,int>> adj[]) {
visited[node] = [1];
for (auto it : adj[node]) {
if (!visited[it.first]) {
topoSort(it.first, visited, st, adj);
}
}
st.push(node);
}Marking the node as true means it is visited to avoid revisiting.
Fill both blanks to complete the loop that processes nodes in topological order and relaxes edges.
while (!st.empty()) { int u = st.top(); st.pop(); if (dist[u] != INT_MAX) { for (auto it : adj[u]) { int v = it.[1]; int weight = it.[2]; if (dist[u] + weight < dist[v]) { dist[v] = dist[u] + weight; } } } }
Each adjacency list element is a pair where first is the node and second is the weight.
Fill the blanks to initialize the graph, perform topological sort, and compute shortest paths.
int V = [1]; vector<pair<int,int>> adj[V]; // Add edges adj[0].push_back({1, 5}); adj[0].push_back({2, 3}); vector<bool> visited(V, false); stack<int> st; for (int i = 0; i < V; i++) { if (!visited[i]) { topoSort(i, visited, st, adj); } } vector<int> dist(V, INT_MAX); dist[[2]] = 0; // Relax edges while (!st.empty()) { int u = st.top(); st.pop(); if (dist[u] != INT_MAX) { for (auto it : adj[u]) { int v = it.first; int weight = it.second; if (dist[u] + weight < dist[v]) { dist[v] = dist[u] + weight; } } } } cout << "Shortest distances from source:" << endl; for (int i = 0; i < V; i++) { cout << i << " -> " << dist[i] << endl; }
We set V=3 for 3 nodes, source node as 0.
