-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy path30_longest_path_in_directed_acyclic_graph.cpp
75 lines (60 loc) · 1.72 KB
/
30_longest_path_in_directed_acyclic_graph.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
link: https://www.geeksforgeeks.org/find-longest-path-directed-acyclic-graph/
logic: read intro in link
video: https://youtu.be/jdTnoCBSOVM
*/
// ----------------------------------------------------------------------------------------------------------------------- //
#include<bits/stdc++.h>
#define int long long int
#define pb push_back
#define ps(x,y) fixed<<setprecision(y)<<x
#define mod 1000000007
#define w(x) int x; cin>>x; while(x--)
using namespace std;
vector<int> order;
void topo(int src, vector<int>& vis, vector<vector<pair<int, int> > > g) {
vis[src] = 1;
for (auto x : g[src]) {
if (!vis[x.first])
topo(x.first, vis, g);
}
order.push_back(src);
}
int32_t main() {
int v, e;
cin >> v >> e;
int src;
cin >> src;
vector<vector<pair<int, int> > > g(v);
for (int i = 0;i < e;i++) {
int x, y, w;
cin >> x >> y >> w;
g[x].push_back({ y,w });
}
vector<int> vis(v, 0);
for (int i = 0;i < v;i++) {
if (!vis[i]) {
topo(i, vis, g);
}
}
vector<int> dist(v);
for (int i = 0;i < v;i++) dist[i] = INT_MIN;
dist[src] = 0;
for (int i = v - 1;i >= 0;i--) {
if (dist[order[i]] != INT_MIN) {
for (auto x : g[order[i]]) {
int v = dist[x.first];
int w = x.second;
int u = dist[order[i]];
if (u + w > v)
dist[x.first] = u + w;
}
}
}
for (int i = 0;i < v;i++) {
if (i != src and dist[i] != INT_MIN) {
cout << src << " -> " << i << " = " << dist[i] << endl;
}
}
return 0;
}