SlideShare a Scribd company logo
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

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

AI Lab menu for ptu students and easy to use and best quality and help for 6t...
AI Lab menu for ptu students and easy to use and best quality and help for 6t...AI Lab menu for ptu students and easy to use and best quality and help for 6t...
AI Lab menu for ptu students and easy to use and best quality and help for 6t...Sonu880062
 
using set identitiesSolutionimport java.util.Scanner; c.pdf
using set identitiesSolutionimport java.util.Scanner;  c.pdfusing set identitiesSolutionimport java.util.Scanner;  c.pdf
using set identitiesSolutionimport java.util.Scanner; c.pdfexcellentmobilesabc
 
TSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) DropboxTSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) DropboxSeb Sear
 
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docxAdamq0DJonese
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdfSpam92
 
Unit 8
Unit 8Unit 8
Unit 8siddr
 
Program of sorting using shell sort #include stdio.h #de.pdf
 Program of sorting using shell sort  #include stdio.h #de.pdf Program of sorting using shell sort  #include stdio.h #de.pdf
Program of sorting using shell sort #include stdio.h #de.pdfanujmkt
 
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...Khoa Mac Tu
 
Program To change this license header, choose License Heade.pdf
Program  To change this license header, choose License Heade.pdfProgram  To change this license header, choose License Heade.pdf
Program To change this license header, choose License Heade.pdfannaelctronics
 
Link Prediction in the Real World
Link Prediction in the Real WorldLink Prediction in the Real World
Link Prediction in the Real WorldBalaji Ganesan
 
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx
Find an LCS of X = and Y = Show the c and b table. Attach File .docxAbdulrahman890100
 
Write a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfWrite a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfjillisacebi75827
 
I need some help to correct this code Instructions The following progr.docx
I need some help to correct this code Instructions The following progr.docxI need some help to correct this code Instructions The following progr.docx
I need some help to correct this code Instructions The following progr.docxPhil4IDBrownh
 
Add a 3rd field help that contains a short help string for each of t.pdf
Add a 3rd field help that contains a short help string for each of t.pdfAdd a 3rd field help that contains a short help string for each of t.pdf
Add a 3rd field help that contains a short help string for each of t.pdfinfo245627
 
Using an Array include ltstdiohgt include ltmpih.pdf
Using an Array include ltstdiohgt include ltmpih.pdfUsing an Array include ltstdiohgt include ltmpih.pdf
Using an Array include ltstdiohgt include ltmpih.pdfgiriraj65
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfmail931892
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfezonesolutions
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof SkarupaSunscrapers
 

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

AI Lab menu for ptu students and easy to use and best quality and help for 6t...
AI Lab menu for ptu students and easy to use and best quality and help for 6t...AI Lab menu for ptu students and easy to use and best quality and help for 6t...
AI Lab menu for ptu students and easy to use and best quality and help for 6t...
 
using set identitiesSolutionimport java.util.Scanner; c.pdf
using set identitiesSolutionimport java.util.Scanner;  c.pdfusing set identitiesSolutionimport java.util.Scanner;  c.pdf
using set identitiesSolutionimport java.util.Scanner; c.pdf
 
TSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) DropboxTSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) Dropbox
 
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docx
 
Pointer
PointerPointer
Pointer
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
 
Unit 8
Unit 8Unit 8
Unit 8
 
Program of sorting using shell sort #include stdio.h #de.pdf
 Program of sorting using shell sort  #include stdio.h #de.pdf Program of sorting using shell sort  #include stdio.h #de.pdf
Program of sorting using shell sort #include stdio.h #de.pdf
 
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
A study on_contrast_and_comparison_between_bellman-ford_algorithm_and_dijkstr...
 
Program To change this license header, choose License Heade.pdf
Program  To change this license header, choose License Heade.pdfProgram  To change this license header, choose License Heade.pdf
Program To change this license header, choose License Heade.pdf
 
Link Prediction in the Real World
Link Prediction in the Real WorldLink Prediction in the Real World
Link Prediction in the Real World
 
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
 
Write a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfWrite a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdf
 
I need some help to correct this code Instructions The following progr.docx
I need some help to correct this code Instructions The following progr.docxI need some help to correct this code Instructions The following progr.docx
I need some help to correct this code Instructions The following progr.docx
 
Singly Linked List
Singly Linked ListSingly Linked List
Singly Linked List
 
Add a 3rd field help that contains a short help string for each of t.pdf
Add a 3rd field help that contains a short help string for each of t.pdfAdd a 3rd field help that contains a short help string for each of t.pdf
Add a 3rd field help that contains a short help string for each of t.pdf
 
Using an Array include ltstdiohgt include ltmpih.pdf
Using an Array include ltstdiohgt include ltmpih.pdfUsing an Array include ltstdiohgt include ltmpih.pdf
Using an Array include ltstdiohgt include ltmpih.pdf
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdf
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
 
Swift - Krzysztof Skarupa
Swift -  Krzysztof SkarupaSwift -  Krzysztof Skarupa
Swift - Krzysztof Skarupa
 

More from anandf0099

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

More from anandf0099 (20)

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

Recently uploaded

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasiemaillard
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptxmansk2
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxakshayaramakrishnan21
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxricssacare
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxShibin Azad
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringDenish Jangid
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasiemaillard
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...Denish Jangid
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxCapitolTechU
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfVivekanand Anglo Vedic Academy
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxRaedMohamed3
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleCeline George
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersPedroFerreira53928
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxbennyroshan06
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 

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"); }