Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7688acd

Browse files
Longest simple path in directed acyclic graph in O(V+E)
1 parent dbe4a7b commit 7688acd

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/* Amit Bansal - @amitbansal7 */
2+
#include <iostream>
3+
#include <vector>
4+
#include <stack>
5+
#include <limits.h>
6+
#define NINF INT_MIN
7+
using namespace std;
8+
using namespace std;
9+
10+
/* Longest simple path in directed acyclic graph in O(V+E) */
11+
12+
void TopologicalSort(vector <pair<int, int> >adj[], int s, bool visited[], stack <int> &S)
13+
{
14+
visited[s] = true;
15+
16+
vector<pair<int, int> >::iterator it;
17+
for (it = adj[s].begin(); it != adj[s].end(); it++)
18+
if (!visited[it->first])
19+
TopologicalSort(adj, it->first, visited, S);
20+
21+
22+
S.push(s);
23+
}
24+
25+
void LSPDAG(vector <pair<int, int> >adj[], int s, int v)
26+
{
27+
stack <int> S;
28+
bool visited[v];
29+
memset(visited, false, sizeof(visited));
30+
31+
for (int i = 0; i < v; i++)
32+
if (!visited[i])
33+
TopologicalSort(adj, i, visited, S);
34+
35+
int dist[v];
36+
37+
for(int i=0;i<v;i++)
38+
dist[i] = NINF;
39+
40+
dist[s] = 0;
41+
42+
while (!S.empty())
43+
{
44+
int u = S.top();
45+
S.pop();
46+
47+
if (dist[u] != NINF)
48+
{
49+
vector <pair<int, int> >::iterator it;
50+
for (it = adj[u].begin(); it != adj[u].end(); ++it)
51+
if (dist[it->first] < dist[u] + it->second)
52+
dist[it->first] = dist[u] + it->second;
53+
}
54+
55+
}
56+
57+
for (int i = 0; i < v; i++)
58+
(dist[i] == NINF) ? cout << "-INF " : cout << dist[i] << " ";
59+
60+
printf("\n");
61+
}
62+
63+
int main()
64+
{
65+
vector <pair<int, int> >adj[6];
66+
67+
adj[0].push_back(make_pair(1, 5));
68+
adj[0].push_back(make_pair(2, 3));
69+
adj[1].push_back(make_pair(3, 6));
70+
adj[1].push_back(make_pair(2, 2));
71+
adj[2].push_back(make_pair(4, 4));
72+
adj[2].push_back(make_pair(5, 2));
73+
adj[2].push_back(make_pair(3, 7));
74+
adj[3].push_back(make_pair(5, 1));
75+
adj[3].push_back(make_pair(4, -1));
76+
adj[4].push_back(make_pair(5, -2));
77+
78+
LSPDAG(adj, 1, 6);
79+
80+
return 0;
81+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /