-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdagshortestpath.cpp
More file actions
97 lines (93 loc) · 2.14 KB
/
Copy pathdagshortestpath.cpp
File metadata and controls
97 lines (93 loc) · 2.14 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution
{
public:
void toposort(int node, vector<pair<int, int>> adj[], vector<int> &vis, stack<int> &st)
{
vis[node] = 1;
for (auto it : adj[node])
{
int k = it.first;
if (vis[k] == 0)
{
toposort(k, adj, vis, st);
}
}
st.push(node);
}
vector<int> shortestPath(int N, int M, vector<vector<int>> &edges)
{
// code here
vector<pair<int, int>> adj[N];
for (int i = 0; i < M; i++)
{
int u = edges[i][0];
int v = edges[i][1];
int wt = edges[i][2];
adj[u].push_back({v, wt});
}
vector<int> vis(N, 0);
stack<int> st;
for (int i = 0; i < N; i++)
{
if (vis[i] == 0)
toposort(i, adj, vis, st);
}
int k = 1e9;
vector<int> dist(N, k);
dist[0] = 0;
while (!st.empty())
{
int node = st.top();
st.pop();
for (auto it : adj[node])
{
int v = it.first;
int wt = it.second;
dist[v] = min(dist[v], dist[node] + wt);
}
}
for (int i = 1; i < N; i++)
{
if (dist[i] == 1e9)
dist[i] = -1;
}
return dist;
}
};
//{ Driver Code Starts.
int main()
{
int t;
cin >> t;
while (t--)
{
int n, m;
cin >> n >> m;
vector<vector<int>> edges;
for (int i = 0; i < m; ++i)
{
vector<int> temp;
for (int j = 0; j < 3; ++j)
{
int x;
cin >> x;
temp.push_back(x);
}
edges.push_back(temp);
}
Solution obj;
vector<int> res = obj.shortestPath(n, m, edges);
for (auto x : res)
{
cout << x << " ";
}
cout << "\n";
}
}
// } Driver Code Ends