using
System;
using
System.Collections.Generic;
class
AdjListNode {
private
int
v;
private
int
weight;
public
AdjListNode(
int
_v,
int
_w)
{
v = _v;
weight = _w;
}
public
int
getV() {
return
v; }
public
int
getWeight() {
return
weight; }
}
class
Graph {
private
int
V;
private
List<AdjListNode>[] adj;
public
Graph(
int
V)
{
this
.V = V;
adj =
new
List<AdjListNode>[ V ];
for
(
int
i = 0; i < V; i++) {
adj[i] =
new
List<AdjListNode>();
}
}
public
void
AddEdge(
int
u,
int
v,
int
weight)
{
AdjListNode node =
new
AdjListNode(v, weight);
adj[u].Add(node);
}
private
void
TopologicalSortUtil(
int
v,
bool
[] visited,
Stack<
int
> stack)
{
visited[v] =
true
;
for
(
int
i = 0; i < adj[v].Count; i++) {
AdjListNode node = adj[v][i];
if
(!visited[node.getV()])
TopologicalSortUtil(node.getV(), visited,
stack);
}
stack.Push(v);
}
public
void
LongestPath(
int
s)
{
Stack<
int
> stack =
new
Stack<
int
>();
int
[] dist =
new
int
[V];
bool
[] visited =
new
bool
[V];
for
(
int
i = 0; i < V; i++)
visited[i] =
false
;
for
(
int
i = 0; i < V; i++) {
if
(visited[i] ==
false
)
TopologicalSortUtil(i, visited, stack);
}
for
(
int
i = 0; i < V; i++)
dist[i] = Int32.MinValue;
dist[s] = 0;
while
(stack.Count > 0) {
int
u = stack.Pop();
if
(dist[u] != Int32.MinValue) {
for
(
int
i = 0; i < adj[u].Count; i++) {
AdjListNode node = adj[u][i];
if
(dist[node.getV()]
< dist[u] + node.getWeight())
dist[node.getV()]
= dist[u] + node.getWeight();
}
}
}
for
(
int
i = 0; i < V; i++) {
if
(dist[i] == Int32.MinValue)
Console.Write(
"INF "
);
else
Console.Write(dist[i] +
" "
);
}
Console.WriteLine();
}
}
public
class
GFG {
static
void
Main(
string
[] args)
{
Graph g =
new
Graph(6);
g.AddEdge(0, 1, 5);
g.AddEdge(0, 2, 3);
g.AddEdge(1, 3, 6);
g.AddEdge(1, 2, 2);
g.AddEdge(2, 4, 4);
g.AddEdge(2, 5, 2);
g.AddEdge(2, 3, 7);
g.AddEdge(3, 5, 1);
g.AddEdge(3, 4, -1);
g.AddEdge(4, 5, -2);
int
s = 1;
Console.WriteLine(
"Following are longest distances from source vertex {0}"
,
s);
g.LongestPath(s);
}
}