-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestPathInDAG.cpp
More file actions
59 lines (49 loc) · 1.21 KB
/
Copy pathShortestPathInDAG.cpp
File metadata and controls
59 lines (49 loc) · 1.21 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
#include<bits/stdc++.h>
using namespace std;
void dfs(int node, vector<vector<pair<int,int>>> graph, vector<bool> &visited, stack<int> &container) {
visited[node] = true;
for(pair<int,int> currNode : graph[node]) {
if(!visited[currNode.first]) {
dfs(currNode.first, graph, visited, container);
}
}
container.push(node);
}
int main() {
int n, m, from, to, weight, src;
cin >> n >> m;
vector<vector<pair<int,int>>> graph(n);
for(int i = 0; i < m; ++i) {
cin >> from >> to >> weight;
graph[from].push_back({to, weight});
}
vector<bool> visited(n, false);
stack<int> container;
for(int node = 0; node < n; ++node) {
if(!visited[node]) {
dfs(node, graph, visited, container);
}
}
cin >> src;
vector<int> distance(n, INT_MAX);
distance[src] = 0;
while(!container.empty() && container.top() != src) {
container.pop();
}
while(!container.empty()) {
int node = container.top();
for(pair<int,int> currNode : graph[node]) {
if(distance[node] + currNode.second < distance[currNode.first]) {
distance[currNode.first] = distance[node] + currNode.second;
}
}
container.pop();
}
for(int x : distance) {
if(x == INT_MAX)
cout << "-1 ";
else
cout << x << " ";
}
return 0;
}