-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfind-longest-path-directed-acyclic-graph.cpp
More file actions
59 lines (54 loc) · 1.07 KB
/
find-longest-path-directed-acyclic-graph.cpp
File metadata and controls
59 lines (54 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// https://www.geeksforgeeks.org/find-longest-path-directed-acyclic-graph/
#include <bits/stdc++.h>
using namespace std;
struct vec{
int src,dst;
int wt;
};
void topSort(int visited[], stack<int> &s, int v, vector<vector<vec> > &g){
visited[v] = 1;
for(int i=0;i<g[v].size();i++){
if(!visited[g[v][i].dst])
topSort(visited, s,g[v][i].dst,g);
}
s.push(v);
}
int main(){
int v = 5, e = 7;
vector<vector<vec> > g;
g.resize(v+1);
vec temp;
for(int i=0;i<e;i++){
cin>>temp.src>>temp.dst>>temp.wt;
g[temp.src].push_back(temp);
}
int visited[100];
int dist[100];
stack<int> s;
for(int i=0;i<=v;i++){
visited[i] = 0;
dist[i] = -INT_MAX;
}
dist[0] = 0;
for(int i=0;i<v;i++){
if(!visited[i]){
topSort(visited,s,i,g);
}
}
vector<int> top;
while(!s.empty()){
top.push_back(s.top());
s.pop();
}
for(int i=0;i<v;i++){
for(int j=0;j<g[top[i]].size();j++){
if(dist[g[top[i]][j].src] < dist[i] + g[top[i]][j].wt)
dist[g[top[i]][j].src] = dist[i] + g[top[i]][j].wt;
}
}
for(int i=0;i<=v;i++){
cout << dist[i] << " ";
}
cout << endl;
return 0;
}