Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 66b8348

Browse files
Add Dijkstra
1 parent 2b61ad4 commit 66b8348

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

‎dijkstra.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include <bits/stdc++.h>
2+
#define ll long long
3+
#define INF 1e18
4+
using namespace std;
5+
6+
vector<vector<pair<ll,ll>>> adj;
7+
vector<ll> dist;
8+
set<pair<ll,ll>> active_vertices;
9+
10+
void dijkstra(ll u) {
11+
ll v,w;
12+
dist[u] = 0;
13+
active_vertices.insert({0, u});
14+
15+
while (!active_vertices.empty()) {
16+
auto it = active_vertices.begin();
17+
u = it->second;
18+
active_vertices.erase(it);
19+
for (auto neighbour : adj[u]) {
20+
v = neighbour.first;
21+
w = neighbour.second;
22+
if (dist[u] + w < dist[v]) {
23+
it = active_vertices.find({dist[v], v});
24+
if (it != active_vertices.end()) {
25+
active_vertices.erase(it);
26+
}
27+
dist[v] = dist[u] + w;
28+
active_vertices.insert({dist[v], v});
29+
}
30+
}
31+
}
32+
}
33+
34+
int main() {
35+
ll i, n, m, u, v, w, src;
36+
cin >> n >> m;
37+
adj.resize(n+1);
38+
dist.assign(n+1, INF);
39+
40+
for (i = 0; i < m; i++) {
41+
cin >> u >> v >> w;
42+
adj[u].push_back({v,w});
43+
adj[v].push_back({u,w});
44+
}
45+
cin >> src;
46+
47+
dijkstra(src);
48+
for (i = 1; i <= n; i++) {
49+
cout << i << " " << dist[i] << endl;
50+
}
51+
return 0;
52+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /