-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdijkstra.cpp
More file actions
77 lines (69 loc) · 1.47 KB
/
Copy pathdijkstra.cpp
File metadata and controls
77 lines (69 loc) · 1.47 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
#include <bits/stdc++.h>
using namespace std;
const int inf = 1e7;
int main()
{
int n, m;
cin >> n >> m;
vector<int> dist(n + 1, inf);
vector<vector<pair<int, int>>> graph(n + 1);
for (int i = 0; i < m; i++)
{
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back({v, w});
graph[v].push_back({u, w});
}
int source;
cin >> source;
dist[source] = 0;
set<pair<int, int>> s;
for (int i = 1; i <= n; i++)
{
if (dist[i] < inf)
cout << dist[i] << "\t";
else
cout << -1 << "\t";
}
cout << "\n";
// {wt, vertex}
s.insert({0, source});
while (!s.empty())
{
auto x = *(s.begin());
s.erase(x);
for (auto i : graph[x.second])
{
if (dist[i.first] > dist[x.second] + i.second)
{
s.erase({dist[i.first], i.first});
dist[i.first] = dist[x.second] + i.second;
s.insert({dist[i.first], i.first});
}
}
for (int i = 1; i <= n; i++)
{
if (dist[i] < inf)
cout << dist[i] << "\t";
else
cout << -1 << "\t";
}
cout << "\n";
}
cout << "final output: \t";
for (int i = 1; i <= n; i++)
{
if (dist[i] < inf)
cout << dist[i] << "\t";
else
cout << -1 << "\t";
}
}
/*
4 4
1 2 24
1 4 20
3 1 3
4 3 12
1
*/