forked from imnurav/Hactoberfest2021-Cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijktras.cpp
61 lines (51 loc) · 1.07 KB
/
dijktras.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
#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000000;
vector<vector<pair<int, int>>> adj;
void dijkstra(int s, vector<int> &d, vector<int> &p)
{
int n = adj.size();
d.assign(n, INF);
p.assign(n, -1);
vector<bool> u(n, false);
d[s] = 0;
for (int i = 0; i < n; i++)
{
int v = -1;
for (int j = 0; j < n; j++)
{
if (!u[j] && (v == -1 || d[j] < d[v]))
v = j;
}
if (d[v] == INF)
break;
u[v] = true;
for (auto edge : adj[v])
{
int to = edge.first;
int len = edge.second;
if (d[v] + len < d[to])
{
d[to] = d[v] + len;
p[to] = v;
}
}
}
}
int main()
{
int n, m, a, b, w;
cin >> n >> m;
while (m--)
{
cin >> a >> b >> w;
adj[a].push_back({b, w});
adj[b].push_back({a, w});
}
vector<int> d, p;
dijkstra(1, d, p);
for (int i = 1; i <= n; i++)
{
cout << d[i] << " ";
}
}