Question

Design an efficient algorithm to find the longest path in a directed acyclic graph. (Must handle...

Design an efficient algorithm to find the longest path in a directed acyclic graph. (Must handle general real-valued weights on the edges, including negative values.) Use C, Java, or Python.

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

//JAVA PROGRAM TO FIND THE LONGEST PATH IN A WEIGHTED DIRECTED ACYCLIC GRAPH HANDLING //REAL AND NEGATIVE WEIGHTS

import java.util.*;
class Edge   // Data structure to store graph edges
{
   int source, dest, weight;

   public Edge(int source, int dest, int weight) {
       this.source = source;
       this.dest = dest;
       this.weight = weight;
   }
};
class Graph
{
   // A List of Lists to represent an adjacency list
   List<List<Edge>> adjList = null;

   // Constructor
   Graph(List<Edge> edges, int N) {
       adjList = new ArrayList<>(N);

       for (int i = 0; i < N; i++) {
           adjList.add(i, new ArrayList<>());
       }

       // add edges to the undirected graph
       for (Edge edge: edges) {
           adjList.get(edge.source).add(edge);
       }
   }
}

class Main
{
   private static int DFS(Graph graph, int v, boolean[] discovered,
                           int[] departure, int time)
   {
       discovered[v] = true;

       for (Edge e : graph.adjList.get(v))
       {
           int u = e.dest;
           if (!discovered[u]) {
               time = DFS(graph, u, discovered, departure, time);
           }
       }
       departure[time] = v;
       time++;

       return time;
   }

   // The function performs topological sort on a given DAG and then finds out the longest distance of all vertices
   // from given source by running one pass of Bellman-Ford algorithm on edges of vertices in topological order

   public static void findLongestDistance(Graph graph, int source, int N)
   {
       int[] departure = new int[N];
       Arrays.fill(departure, -1);
       boolean[] discovered = new boolean[N];
       int time = 0;
       for (int i = 0; i < N; i++) {
           if (!discovered[i]) {
               time = DFS(graph, i, discovered, departure, time);
           }
       }

       int[] cost = new int[N];
       Arrays.fill(cost, Integer.MAX_VALUE);

       cost[source] = 0;

       // Process the vertices in topological order i.e. in order of their decreasing departure time in DFS
      
       for (int i = N - 1; i >= 0; i--)
       {
           int v = departure[i];
           for (Edge e : graph.adjList.get(v))
           {
               int u = e.dest;
               int w = e.weight * -1;   // negative the weight of edge
               if (cost[v] != Integer.MAX_VALUE && cost[v] + w < cost[u]) {
                   cost[u] = cost[v] + w;
               }
           }
       }

       for (int i = 0; i < N; i++)
       {
           System.out.printf("dist(%d, %d) = %2d\n", source, i, cost[i] * -1);
       }
   }

   public static void main(String[] args)
   {
       List<Edge> edges = Arrays.asList(
                               new Edge(0, 6, 8), new Edge(1, 2, -4), ///Edge(source,destination,weight)
                               new Edge(1, 4, 4), new Edge(1, 6, 4),
                               new Edge(3, 0, 2), new Edge(3, 4, 7),
                               new Edge(5, 1, -2), new Edge(7, 0, 2),
                               new Edge(7, 1, 6), new Edge(7, 3, 4),
                               new Edge(7, 5, 4)
                           );   

       final int N = 8; // number of vertices in the graph
       Graph graph = new Graph(edges, N);   // create a graph from given edges
       int source = 7;
       findLongestDistance(graph, source, N);
   }
}

Add a comment
Know the answer?
Add Answer to:
Design an efficient algorithm to find the longest path in a directed acyclic graph. (Must handle...
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
  • Longest paths Can you modify Dijkstra’s algorithm to find the length of the longest path from...

    Longest paths Can you modify Dijkstra’s algorithm to find the length of the longest path from a vertex s to another vertex t in a directed acyclic graph?

  • 2. Design a deterministic algorithm to solve the following problem. input: A directed acyclic graph G...

    2. Design a deterministic algorithm to solve the following problem. input: A directed acyclic graph G = (V, E) stored using adjacency lists. output: A Hamiltonian path, if such a path exists. Otherwise, return NONE. Your algorithm must take O(|V| + |E|) time. You must describe your algorithm in plain English (no pseudocode) and you must explain why the running time of your algorithm is O(|V| + |E|). Maximum half a page

  • Consider a directed acyclic graph G = (V, E) without edge lengths and a start vertex...

    Consider a directed acyclic graph G = (V, E) without edge lengths and a start vertex s E V. (Recall, the length of a path in an graph without edge lengths is given by the number of edges on that path). Someone claims that the following greedy algorithm will always find longest path in the graph G starting from s. path = [8] Ucurrent = s topologically sort the vertices V of G. forall v EV in topological order do...

  • 3. Give an efficient algorithm that takes as input a directed graph G-(V,E) with edges labeled wi...

    Please show your work 3. Give an efficient algorithm that takes as input a directed graph G-(V,E) with edges labeled with either 0 or 1, and vertices s and t that ouputs TRUE if and only if there is a path (not necessarily simple) that goes from s to t such that the binary sequence of edges in the path avoids the substring "11" and outputs FALSE otherwise. (For example, the string 10100010 avoids 11 but the string 00101101110 does...

  • Question 1.) Given a directed negative weights Graph what is the most efficient algorithm to detect...

    Question 1.) Given a directed negative weights Graph what is the most efficient algorithm to detect a cycle. What is the most efficient method to detect a cycle? Question 2.)Let A= student id last digit % 4 and add 1. For example mine student id is 7. So 7%4=3 and add 1 -->A=4 Run DFS starting at node a, and breaking ties alphabetically(in this case numerically as nodes have numbers where 1 goes before 2). Please label just back edges....

  • PYTHON ONLY Implement the Dijkstra’s Shortest path algorithm in Python. A graph with 10 nodes (Node...

    PYTHON ONLY Implement the Dijkstra’s Shortest path algorithm in Python. A graph with 10 nodes (Node 0 to node 9) must be implemented. You are supposed to denote the distance of the edges via an adjacency matrix (You can assume the edge weights are either 0 or a positive value). The adjacency matrix is supposed to be a 2-D array and it is to be inputted to the graph. Remember that the adjacency list denotes the edge values for the...

  • Viterbi algorithm We can use dynamic programming on a directed graph G = (V, E) for...

    Viterbi algorithm We can use dynamic programming on a directed graph G = (V, E) for speech recognition. Each edge (u, v) in E is labeled with a sound s(u, v) from a finite set S of sounds. The labeled graph is a formal model of a person speaking a restricted language. Each path in the graph starting from a distinguished vertex v0 in V corresponds to a possible sequence of sounds produced by the model. The label of a...

  • you wish to design a dungeon-crawl style video game which you can model as a directed...

    you wish to design a dungeon-crawl style video game which you can model as a directed graph. The dungeon is constructed of rooms, each of which has corridors that lead to other rooms. Each corridor (directed edge) in the dungeon has either a monster or an item of value, and you score positive or negative points depending on which is present. To win the game, you must find a path from room to room, from the entrance door s to...

  • a. (15 marks) i (7 marks) Consider the weighted directed graph below. Carry out the steps...

    a. (15 marks) i (7 marks) Consider the weighted directed graph below. Carry out the steps of Dijkstra's shortest path algorithm as covered in lectures, starting at vertex S. Consequently give the shortest path from S to vertex T and its length 6 A 2 3 4 S T F ii (2 marks) For a graph G = (V, E), what is the worst-case time complexity of the version of Dijkstra's shortest path algorithm examined in lectures? (Your answer should...

  • Find the shortest path algorithm tables (for the graph on the homework sheet) using the (a)...

    Find the shortest path algorithm tables (for the graph on the homework sheet) using the (a) Dijkstra algorithm (b) Ford-Fulkerson algorithm Label the columns B,C,D from left to right. Node A is the root node. Use pointers for only the Ford Fulkerson algorithm as in the Networks and Grids book. (c) Let the link number be bandwidth (data rate). Create the routing table that allows you find paths to the root node that maximize the bottleneck bandwidth Uhe

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