-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortestPathdirectedweightedGraph.cpp
59 lines (50 loc) · 1.1 KB
/
shortestPathdirectedweightedGraph.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
#include<bits/stdc++.h>
#include<iostream>
#define INF INT_MAX
using namespace std;
void findTopoSort(int node, int vis[], stack<int> &st, vector<pair<int,int>> adj[]){
vis[node]=1;
for(auto it: adj[node]){
if(!vis[it.first]){
findTopoSort(it.first, vis, st, adj);
}
}
st.push(node);
}
void shortestPath(int src, int N, vector<pair<int,int>> adj[])
{
int vis[N]={0};
stack<int>st;
for(int i=0;i<N;i++)
if(!vis[i])
findTopoSort(i,vis,st,adj);
int dist[N];
for(int i=0;i<N;i++)
dist[i]=1e9;
dist[src]=0;
while(!st.empty()) {
int node=st.top();
st.pop();
if(dist[node]!=INF){
for(auto it:adj[node]){
if(dist[node]+it.second < dist[it.first]){
dist[it.first]=dist[node]+it.second;
}
}
}
}
for(int i=0;i<N;i++)
(dist[i]==1e9)? cout<<"INF": cout<< dist[i]<< " ";
}
int main() {
int n,m;
cin>>n>>m;
vector<pair><int,int>> adj[n];
for(int i=0;i<m;i++){
int u,v,wt;
cin>>u>>v>>wt;
adj[u].push_back({v,wt});
}
shortestPath(0,n, adj);
return 0;
}