Question

Problem 1: Dynamic Programming in DAG Let G(V,E), |V| = n, be a directed acyclic graph...

Problem 1: Dynamic Programming in DAG

Let G(V,E), |V| = n, be a directed acyclic graph presented in adjacency list representation, where the vertices are labelled with numbers in the set {1, . . . , n}, and where (i, j) is and edge inplies i < j. Suppose also that each vertex has a positive value vi, 1 ≤ i ≤ n. Define the value of a path as the sum of the values of the vertices belonging to the path. Give an O(|V | + |E|) algorithm that finds the path of maximum value in the graph.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Algorithm:

Approach:

We run a dfs to the graph and we calculate longest path from a node.

The longest path from a node is 1 plus maximum of longest path among all of it's children.

After calculating maximum distance for all the nodes of the directed acyclic graph we find the maximum among them and that will be the longest path in the graph.

Steps:

  • V = vertices count
  • val [ ] = array of values of vertices
  • dist[ V+1 ] = { 0 }
  • visited [ V+1 ] = {false}
  • for u = 1 to V
    • if visited[u] == false
      • then call dfs(u, visited, value, dist) // this will fill the dist[] array
  • longest_path = 0
  • for u = 1 to V
    • longest_path = max(longest_path, dist[u])

// recursive dfs

  • dfs(u, visited[ ], value[ ], dist[ ])
    • visited[u] = true
    • dist[u] = value[u]
    • for v in adj[u]
      • if visited[v] == false
        • dfs(v, visited, value, dist[ ]) // recursion
      • dist[u] = max(dist[u] , value[u] + dist[v] ) // calculating dist

Implementation in C++:

1 #include <bits/stdc++.h> using namespace std; void dfs(int node, vector int> adj[], int dp[], bool vis[]) { vis(node] = tru​​​​​​​

Sample output:

3

Time complexity:

Since we are running a dfs in the graph and we have adjacency matrix given. So, the time complexity of this algorithm would be same as dfs which is O(|V|+|E|) .

If the answer helped please upvote, it means a lot and for any query please comment.

Add a comment
Know the answer?
Add Answer to:
Problem 1: Dynamic Programming in DAG Let G(V,E), |V| = n, be a directed acyclic graph...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT