i have written ths code as per your requirements with clear comments as shown below with
output
package com.sanfoundry.hardgraph;
import java.util.Scanner;
import java.util.Vector;
class Node1
{
int name; // node ID, started from 0 to n-1
Vector preds; // predecessors (String)
Vector neibs; // neighbors (String)
Vector backs; // backward edges -node is end vertex (Integer)
Vector fors; // forward edges -node is start vertex (Integer)
int pNode; // previous node on the augmenting path
int pEdge; // from which edge this node comes on the augmenting
// path
public Node1(int id)
{
name = id;
backs = new Vector();
fors = new Vector();
pNode1 = -1;
pEdge = -1;
}
}
class Edge
{
int name; // edge ID, started from 0 to n-1
int start; // start vertex of this edge
int end; // end vertex of this edge
int direct; // forwards (+1) or backwards (-1) on augmenting path
// if 0 then not part of augmenting path
int capacity; // capacity
int flow; // current flow
public Edge(int id)
{
name = id;
start = -1;
end = -1;
direct = 0; // default is neither
capacity = 0;
flow = 0;
}
public String toString()
{
return name + ": s=" + start + " e=" + end + " d=" + direct;
}
}
public class LongestPathinDAG
{
int n; // number of nodes
int target; // destination node
int minLength; // the minimal length of each path
Node1[] v; // used to store Nodes
Edge[] e; // used to store Edges
int[] path; // used to store temporary path
int length = 0; // length of the path
int distance = 0; // distance of the path
int[] bestPath; // used to store temporary path
int bestLength = 0; // length of the longest path
int bestDistance = -1000000; // distance of the longest path
int[] visited; // used to mark a node as visited if set as
// 1
public LongestPathinDAG()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of vertices: ");
n = sc.nextInt();
System.out.println("Enter the number of edges: ");
int m = sc.nextInt();
v = new Node1[n];
e = new Edge[m];
System.out.println(n + " nodes and " + m + " edges.");
for (int i = 0; i < n; i++)
v[i] = new Node1(i);
int i = 0;
while (i < e.length)
{
Edge edge = new Edge(i);
int sVal = sc.nextInt();
edge.start = sVal;// sc.nextInt();
int eVal = sc.nextInt();
edge.end = eVal;// sc.nextInt();
edge.capacity = sc.nextInt();
System.out.println(" edge: " + edge.start + " - " + edge.end
+ " : " + edge.capacity);
edge.flow = 0;
e[i] = edge;
v[sVal].fors.add(i);
v[eVal].backs.add(i);
i++;
if (i == m)
break;
}
visited = new int[v.length];
path = new int[v.length];
bestPath = new int[v.length];
sc.close();
}
/*
* this function looks for a longest path starting from being to end,
* using the backtrack depth-first search.
*/
public boolean findLongestPath(int begin, int end, int minLen)
{
/*
* compute a longest path from begin to end
*/
target = end;
bestDistance = -100000000;
minLength = minLen;
dfsLongestPath(begin);
if (bestDistance == -100000000)
return false;
else
return true;
}
private void dfsLongestPath(int current)
{
visited[current] = 1;
path[length++] = current;
if (current == target && length >= minLength)
{
if (distance > bestDistance)
{
for (int i = 0; i < length; i++)
bestPath[i] = path[i];
bestLength = length;
bestDistance = distance;
}
}
else
{
Vector fors = v[current].fors;
for (int i = 0; i < fors.size(); i++)
{
Integer edge_obj = (Integer) fors.elementAt(i);
int edge = edge_obj.intValue();
if (visited[e[edge].end] == 0)
{
distance += e[edge].capacity;
dfsLongestPath(e[edge].end);
distance -= e[edge].capacity;
}
}
}
visited[current] = 0;
length--;
}
public String toString()
{
String output = "v" + bestPath[0];
for (int i = 1; i < bestLength; i++)
output = output + " -> v" + bestPath[i];
return output;
}
public static void main(String arg[])
{
LongestPathinDAG lp = new LongestPathinDAG();
/*
* find a longest path from vertex 0 to vertex n-1.
*/
if (lp.findLongestPath(0, lp.n - 1, 1))
System.out.println("Longest Path is " + lp
+ " and the distance is " + lp.bestDistance);
else
System.out.println("No path from v0 to v" + (lp.n - 1));
/*
* find a longest path from vertex 3 to vertex 5.
*/
if (lp.findLongestPath(3, 5, 1))
System.out.println("Longest Path is " + lp
+ " and the distance is " + lp.bestDistance);
else
System.out.println("No path from v3 to v5");
/*
* find a longest path from vertex 5 to vertex 3.
*/
if (lp.findLongestPath(lp.n - 1, 3, 1))
System.out.println("Longest Path is " + lp
+ " and the distance is " + lp.bestDistance);
else
System.out.println("No path from v5 to v3");
}
}
output
Solution
i have written ths code as per your requirements with clear comments as shown below with
output
package com.sanfoundry.hardgraph;
import java.util.Scanner;
import java.util.Vector;
class Node1
{
int name; // node ID, started from 0 to n-1
Vector preds; // predecessors (String)
Vector neibs; // neighbors (String)
Vector backs; // backward edges -node is end vertex (Integer)
Vector fors; // forward edges -node is start vertex (Integer)
int pNode; // previous node on the augmenting path
int pEdge; // from which edge this node comes on the augmenting
// path
public Node1(int id)
{
name = id;
backs = new Vector();
fors = new Vector();
pNode1 = -1;
pEdge = -1;
}
}
class Edge
{
int name; // edge ID, started from 0 to n-1
int start; // start vertex of this edge
int end; // end vertex of this edge
int direct; // forwards (+1) or backwards (-1) on augmenting path
// if 0 then not part of augmenting path
int capacity; // capacity
int flow; // current flow
public Edge(int id)
{
name = id;
start = -1;
end = -1;
direct = 0; // default is neither
capacity = 0;
flow = 0;
}
public String toString()
{
return name + ": s=" + start + " e=" + end + " d=" + direct;
}
}
public class LongestPathinDAG
{
int n; // number of nodes
int target; // destination node
int minLength; // the minimal length of each path
Node1[] v; // used to store Nodes
Edge[] e; // used to store Edges
int[] path; // used to store temporary path
int length = 0; // length of the path
int distance = 0; // distance of the path
int[] bestPath; // used to store temporary path
int bestLength = 0; // length of the longest path
int bestDistance = -1000000; // distance of the longest path
int[] visited; // used to mark a node as visited if set as
// 1
public LongestPathinDAG()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of vertices: ");
n = sc.nextInt();
System.out.println("Enter the number of edges: ");
int m = sc.nextInt();
v = new Node1[n];
e = new Edge[m];
System.out.println(n + " nodes and " + m + " edges.");
for (int i = 0; i < n; i++)
v[i] = new Node1(i);
int i = 0;
while (i < e.length)
{
Edge edge = new Edge(i);
int sVal = sc.nextInt();
edge.start = sVal;// sc.nextInt();
int eVal = sc.nextInt();
edge.end = eVal;// sc.nextInt();
edge.capacity = sc.nextInt();
System.out.println(" edge: " + edge.start + " - " + edge.end
+ " : " + edge.capacity);
edge.flow = 0;
e[i] = edge;
v[sVal].fors.add(i);
v[eVal].backs.add(i);
i++;
if (i == m)
break;
}
visited = new int[v.length];
path = new int[v.length];
bestPath = new int[v.length];
sc.close();
}
/*
* this function looks for a longest path starting from being to end,
* using the backtrack depth-first search.
*/
public boolean findLongestPath(int begin, int end, int minLen)
{
/*
* compute a longest path from begin to end
*/
target = end;
bestDistance = -100000000;
minLength = minLen;
dfsLongestPath(begin);
if (bestDistance == -100000000)
return false;
else
return true;
}
private void dfsLongestPath(int current)
{
visited[current] = 1;
path[length++] = current;
if (current == target && length >= minLength)
{
if (distance > bestDistance)
{
for (int i = 0; i < length; i++)
bestPath[i] = path[i];
bestLength = length;
bestDistance = distance;
}
}
else
{
Vector fors = v[current].fors;
for (int i = 0; i < fors.size(); i++)
{
Integer edge_obj = (Integer) fors.elementAt(i);
int edge = edge_obj.intValue();
if (visited[e[edge].end] == 0)
{
distance += e[edge].capacity;
dfsLongestPath(e[edge].end);
distance -= e[edge].capacity;
}
}
}
visited[current] = 0;
length--;
}
public String toString()
{
String output = "v" + bestPath[0];
for (int i = 1; i < bestLength; i++)
output = output + " -> v" + bestPath[i];
return output;
}
public static void main(String arg[])
{
LongestPathinDAG lp = new LongestPathinDAG();
/*
* find a longest path from vertex 0 to vertex n-1.
*/
if (lp.findLongestPath(0, lp.n - 1, 1))
System.out.println("Longest Path is " + lp
+ " and the distance is " + lp.bestDistance);
else
System.out.println("No path from v0 to v" + (lp.n - 1));
/*
* find a longest path from vertex 3 to vertex 5.
*/
if (lp.findLongestPath(3, 5, 1))
System.out.println("Longest Path is " + lp
+ " and the distance is " + lp.bestDistance);
else
System.out.println("No path from v3 to v5");
/*
* find a longest path from vertex 5 to vertex 3.
*/
if (lp.findLongestPath(lp.n - 1, 3, 1))
System.out.println("Longest Path is " + lp
+ " and the distance is " + lp.bestDistance);
else
System.out.println("No path from v5 to v3");
}
}
output

More Related Content

DOCX
Write a program that reads a graph from a file and determines whether.docx
PDF
Program To change this license header, choose License Heade.pdf
PDF
JAVA BASED VISUALIZATION AND ANIMATION FOR TEACHING THE DIJKSTRA SHORTEST PAT...
PPT
Graphs
PDF
Dijkstra's shortest path algorithm
PDF
Complete the implementation of the Weighted Graph that we began in t.pdf
DOCX
Write a program that reads a graph from a file anil determines whethe.docx
Write a program that reads a graph from a file and determines whether.docx
Program To change this license header, choose License Heade.pdf
JAVA BASED VISUALIZATION AND ANIMATION FOR TEACHING THE DIJKSTRA SHORTEST PAT...
Graphs
Dijkstra's shortest path algorithm
Complete the implementation of the Weighted Graph that we began in t.pdf
Write a program that reads a graph from a file anil determines whethe.docx

Similar to i have written ths code as per your requirements with clear comments.pdf (20)

PPTX
15-bellmanFord.pptx...........................................
PPTX
kjugyfdtryuytrdtfyugtfdxghjgfdial algorithm.pptx
PPTX
Internet Download Manager Crack Patch Latest IDM Free
PPT
Prim's Algorithm on minimum spanning tree
PDF
#include #include Number of vertices in the graph #define V 9 .pdf
PDF
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
PPT
9_graphs2.v4.ppt
PPT
Graphs, Min Span Tree and Shortest Path Algo
PPT
DOCX
PathOfMostResistance
PPT
Chap07alg
PPT
Chap07alg
DOCX
2 a networkflow
PPT
Directed Acyclic Graph
PDF
CS253: Minimum spanning Trees (2019)
PDF
SHORTEST PATH FINDING VISUALIZER
DOCX
2Part I1. Answer questions for the following graph, if .docx
PDF
Please implement in Java. comments would be appreciated 5.pdf
PDF
COMPUTER NETWORKS AND SECURITY PRACTICAL
PPTX
Graph Algorithms
15-bellmanFord.pptx...........................................
kjugyfdtryuytrdtfyugtfdxghjgfdial algorithm.pptx
Internet Download Manager Crack Patch Latest IDM Free
Prim's Algorithm on minimum spanning tree
#include #include Number of vertices in the graph #define V 9 .pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
9_graphs2.v4.ppt
Graphs, Min Span Tree and Shortest Path Algo
PathOfMostResistance
Chap07alg
Chap07alg
2 a networkflow
Directed Acyclic Graph
CS253: Minimum spanning Trees (2019)
SHORTEST PATH FINDING VISUALIZER
2Part I1. Answer questions for the following graph, if .docx
Please implement in Java. comments would be appreciated 5.pdf
COMPUTER NETWORKS AND SECURITY PRACTICAL
Graph Algorithms

More from anandf0099 (20)

PDF
Riboflavin is required in the conversion of carbo.pdf
PDF
PbS,Ag2O and CaSO4 are stable as they are insolub.pdf
PDF
Optio D is the correct one. .pdf
PDF
Image not seenfound .pdf
PDF
If multiple orbitals of the same energy are avail.pdf
PDF
What is a Distributed System Compare it with a computer network sys.pdf
PDF
USES OF FINANCIAL STATEMENT ANALYSISFINANCIAL STATEMENT ANALYSIS .pdf
PDF
The movement of watersolvent across the osmotic gradient takes plac.pdf
PDF
These groups are closely related not only is SO(2) a subgroup of O(.pdf
PDF
The probability of atom has zero quanta of energy is      P=Number.pdf
PDF
Copper turns green because it oxidizes. Coppe.pdf
PDF
CO2 and NO2 are acidic oxides as non-metal form a.pdf
PDF
Ques-1 Development of tube feet of CRINOIDEADevelopment of tube f.pdf
PDF
Program.csusing System; using System.Collections.Generic; usin.pdf
PDF
B. propene. Solution B. p.pdf
PDF
L{e^{-t}} = int _0 to infinty [e^{st}e^{2-t} dt = int _0 to infinty.pdf
PDF
Issue of Equity or Debt are commonly used methods for business finan.pdf
PDF
In probability we have two types of eventsIndependent Events who.pdf
PDF
Hi,Please fidn the Answer.Sorting,h is Header .pdf
PDF
Fraxinus americana (white ash or American ash) is a species of ash t.pdf
Riboflavin is required in the conversion of carbo.pdf
PbS,Ag2O and CaSO4 are stable as they are insolub.pdf
Optio D is the correct one. .pdf
Image not seenfound .pdf
If multiple orbitals of the same energy are avail.pdf
What is a Distributed System Compare it with a computer network sys.pdf
USES OF FINANCIAL STATEMENT ANALYSISFINANCIAL STATEMENT ANALYSIS .pdf
The movement of watersolvent across the osmotic gradient takes plac.pdf
These groups are closely related not only is SO(2) a subgroup of O(.pdf
The probability of atom has zero quanta of energy is      P=Number.pdf
Copper turns green because it oxidizes. Coppe.pdf
CO2 and NO2 are acidic oxides as non-metal form a.pdf
Ques-1 Development of tube feet of CRINOIDEADevelopment of tube f.pdf
Program.csusing System; using System.Collections.Generic; usin.pdf
B. propene. Solution B. p.pdf
L{e^{-t}} = int _0 to infinty [e^{st}e^{2-t} dt = int _0 to infinty.pdf
Issue of Equity or Debt are commonly used methods for business finan.pdf
In probability we have two types of eventsIndependent Events who.pdf
Hi,Please fidn the Answer.Sorting,h is Header .pdf
Fraxinus americana (white ash or American ash) is a species of ash t.pdf

Recently uploaded (20)

PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PPTX
20th Century Theater, Methods, History.pptx
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
My India Quiz Book_20210205121199924.pdf
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PPTX
Introduction to pro and eukaryotes and differences.pptx
PPTX
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Virtual and Augmented Reality in Current Scenario
PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
Trump Administration's workforce development strategy
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
advance database management system book.pdf
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
20th Century Theater, Methods, History.pptx
Paper A Mock Exam 9_ Attempt review.pdf.
My India Quiz Book_20210205121199924.pdf
Environmental Education MCQ BD2EE - Share Source.pdf
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
Introduction to pro and eukaryotes and differences.pptx
Onco Emergencies - Spinal cord compression Superior vena cava syndrome Febr...
Cambridge-Practice-Tests-for-IELTS-12.docx
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Virtual and Augmented Reality in Current Scenario
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
A powerpoint presentation on the Revised K-10 Science Shaping Paper
Trump Administration's workforce development strategy
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
advance database management system book.pdf
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS

i have written ths code as per your requirements with clear comments.pdf

  • 1. i have written ths code as per your requirements with clear comments as shown below with output package com.sanfoundry.hardgraph; import java.util.Scanner; import java.util.Vector; class Node1 { int name; // node ID, started from 0 to n-1 Vector preds; // predecessors (String) Vector neibs; // neighbors (String) Vector backs; // backward edges -node is end vertex (Integer) Vector fors; // forward edges -node is start vertex (Integer) int pNode; // previous node on the augmenting path int pEdge; // from which edge this node comes on the augmenting // path public Node1(int id) { name = id; backs = new Vector(); fors = new Vector(); pNode1 = -1; pEdge = -1; } } class Edge { int name; // edge ID, started from 0 to n-1 int start; // start vertex of this edge int end; // end vertex of this edge int direct; // forwards (+1) or backwards (-1) on augmenting path // if 0 then not part of augmenting path
  • 2. int capacity; // capacity int flow; // current flow public Edge(int id) { name = id; start = -1; end = -1; direct = 0; // default is neither capacity = 0; flow = 0; } public String toString() { return name + ": s=" + start + " e=" + end + " d=" + direct; } } public class LongestPathinDAG { int n; // number of nodes int target; // destination node int minLength; // the minimal length of each path Node1[] v; // used to store Nodes Edge[] e; // used to store Edges int[] path; // used to store temporary path int length = 0; // length of the path int distance = 0; // distance of the path int[] bestPath; // used to store temporary path int bestLength = 0; // length of the longest path int bestDistance = -1000000; // distance of the longest path int[] visited; // used to mark a node as visited if set as // 1 public LongestPathinDAG()
  • 3. { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of vertices: "); n = sc.nextInt(); System.out.println("Enter the number of edges: "); int m = sc.nextInt(); v = new Node1[n]; e = new Edge[m]; System.out.println(n + " nodes and " + m + " edges."); for (int i = 0; i < n; i++) v[i] = new Node1(i); int i = 0; while (i < e.length) { Edge edge = new Edge(i); int sVal = sc.nextInt(); edge.start = sVal;// sc.nextInt(); int eVal = sc.nextInt(); edge.end = eVal;// sc.nextInt(); edge.capacity = sc.nextInt(); System.out.println(" edge: " + edge.start + " - " + edge.end + " : " + edge.capacity); edge.flow = 0; e[i] = edge; v[sVal].fors.add(i); v[eVal].backs.add(i); i++; if (i == m) break; } visited = new int[v.length]; path = new int[v.length]; bestPath = new int[v.length]; sc.close(); }
  • 4. /* * this function looks for a longest path starting from being to end, * using the backtrack depth-first search. */ public boolean findLongestPath(int begin, int end, int minLen) { /* * compute a longest path from begin to end */ target = end; bestDistance = -100000000; minLength = minLen; dfsLongestPath(begin); if (bestDistance == -100000000) return false; else return true; } private void dfsLongestPath(int current) { visited[current] = 1; path[length++] = current; if (current == target && length >= minLength) { if (distance > bestDistance) { for (int i = 0; i < length; i++) bestPath[i] = path[i]; bestLength = length; bestDistance = distance; } } else { Vector fors = v[current].fors;
  • 5. for (int i = 0; i < fors.size(); i++) { Integer edge_obj = (Integer) fors.elementAt(i); int edge = edge_obj.intValue(); if (visited[e[edge].end] == 0) { distance += e[edge].capacity; dfsLongestPath(e[edge].end); distance -= e[edge].capacity; } } } visited[current] = 0; length--; } public String toString() { String output = "v" + bestPath[0]; for (int i = 1; i < bestLength; i++) output = output + " -> v" + bestPath[i]; return output; } public static void main(String arg[]) { LongestPathinDAG lp = new LongestPathinDAG(); /* * find a longest path from vertex 0 to vertex n-1. */ if (lp.findLongestPath(0, lp.n - 1, 1)) System.out.println("Longest Path is " + lp + " and the distance is " + lp.bestDistance); else System.out.println("No path from v0 to v" + (lp.n - 1)); /*
  • 6. * find a longest path from vertex 3 to vertex 5. */ if (lp.findLongestPath(3, 5, 1)) System.out.println("Longest Path is " + lp + " and the distance is " + lp.bestDistance); else System.out.println("No path from v3 to v5"); /* * find a longest path from vertex 5 to vertex 3. */ if (lp.findLongestPath(lp.n - 1, 3, 1)) System.out.println("Longest Path is " + lp + " and the distance is " + lp.bestDistance); else System.out.println("No path from v5 to v3"); } } output Solution i have written ths code as per your requirements with clear comments as shown below with output package com.sanfoundry.hardgraph; import java.util.Scanner; import java.util.Vector; class Node1 { int name; // node ID, started from 0 to n-1 Vector preds; // predecessors (String) Vector neibs; // neighbors (String) Vector backs; // backward edges -node is end vertex (Integer) Vector fors; // forward edges -node is start vertex (Integer) int pNode; // previous node on the augmenting path
  • 7. int pEdge; // from which edge this node comes on the augmenting // path public Node1(int id) { name = id; backs = new Vector(); fors = new Vector(); pNode1 = -1; pEdge = -1; } } class Edge { int name; // edge ID, started from 0 to n-1 int start; // start vertex of this edge int end; // end vertex of this edge int direct; // forwards (+1) or backwards (-1) on augmenting path // if 0 then not part of augmenting path int capacity; // capacity int flow; // current flow public Edge(int id) { name = id; start = -1; end = -1; direct = 0; // default is neither capacity = 0; flow = 0; } public String toString() { return name + ": s=" + start + " e=" + end + " d=" + direct;
  • 8. } } public class LongestPathinDAG { int n; // number of nodes int target; // destination node int minLength; // the minimal length of each path Node1[] v; // used to store Nodes Edge[] e; // used to store Edges int[] path; // used to store temporary path int length = 0; // length of the path int distance = 0; // distance of the path int[] bestPath; // used to store temporary path int bestLength = 0; // length of the longest path int bestDistance = -1000000; // distance of the longest path int[] visited; // used to mark a node as visited if set as // 1 public LongestPathinDAG() { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of vertices: "); n = sc.nextInt(); System.out.println("Enter the number of edges: "); int m = sc.nextInt(); v = new Node1[n]; e = new Edge[m]; System.out.println(n + " nodes and " + m + " edges."); for (int i = 0; i < n; i++) v[i] = new Node1(i); int i = 0; while (i < e.length) { Edge edge = new Edge(i); int sVal = sc.nextInt();
  • 9. edge.start = sVal;// sc.nextInt(); int eVal = sc.nextInt(); edge.end = eVal;// sc.nextInt(); edge.capacity = sc.nextInt(); System.out.println(" edge: " + edge.start + " - " + edge.end + " : " + edge.capacity); edge.flow = 0; e[i] = edge; v[sVal].fors.add(i); v[eVal].backs.add(i); i++; if (i == m) break; } visited = new int[v.length]; path = new int[v.length]; bestPath = new int[v.length]; sc.close(); } /* * this function looks for a longest path starting from being to end, * using the backtrack depth-first search. */ public boolean findLongestPath(int begin, int end, int minLen) { /* * compute a longest path from begin to end */ target = end; bestDistance = -100000000; minLength = minLen; dfsLongestPath(begin); if (bestDistance == -100000000) return false; else
  • 10. return true; } private void dfsLongestPath(int current) { visited[current] = 1; path[length++] = current; if (current == target && length >= minLength) { if (distance > bestDistance) { for (int i = 0; i < length; i++) bestPath[i] = path[i]; bestLength = length; bestDistance = distance; } } else { Vector fors = v[current].fors; for (int i = 0; i < fors.size(); i++) { Integer edge_obj = (Integer) fors.elementAt(i); int edge = edge_obj.intValue(); if (visited[e[edge].end] == 0) { distance += e[edge].capacity; dfsLongestPath(e[edge].end); distance -= e[edge].capacity; } } } visited[current] = 0; length--; }
  • 11. public String toString() { String output = "v" + bestPath[0]; for (int i = 1; i < bestLength; i++) output = output + " -> v" + bestPath[i]; return output; } public static void main(String arg[]) { LongestPathinDAG lp = new LongestPathinDAG(); /* * find a longest path from vertex 0 to vertex n-1. */ if (lp.findLongestPath(0, lp.n - 1, 1)) System.out.println("Longest Path is " + lp + " and the distance is " + lp.bestDistance); else System.out.println("No path from v0 to v" + (lp.n - 1)); /* * find a longest path from vertex 3 to vertex 5. */ if (lp.findLongestPath(3, 5, 1)) System.out.println("Longest Path is " + lp + " and the distance is " + lp.bestDistance); else System.out.println("No path from v3 to v5"); /* * find a longest path from vertex 5 to vertex 3. */ if (lp.findLongestPath(lp.n - 1, 3, 1)) System.out.println("Longest Path is " + lp + " and the distance is " + lp.bestDistance); else System.out.println("No path from v5 to v3"); }