This repository has been archived by the owner on May 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.cpp
103 lines (92 loc) · 1.96 KB
/
dijkstra.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
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
98
99
100
101
102
103
#include <bits/stdc++.h>
#define for1(s,n) for(int i = s; i < n; i++)
#define for1j(s,n) for(int j = s; j < n; j++)
#define foreach(k) for(auto i : k)
#define foreachj(k) for(auto j : k)
#define pb(a) push_back(a)
#define sz(a) a.size()
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef vector <int> iv1;
typedef vector <vector<int>> iv2;
typedef vector <ll> llv1;
typedef unsigned int uint;
typedef vector <ull> ullv1;
typedef vector <vector <ull>> ullv2;
#define INF (ll)1e18
struct edge {
ll node;
ll cost;
bool operator<(const edge &to) const {
return cost > to.cost;
}
};
struct WGraph {
ll n;
vector<vector<edge>> adj;
vector<ll> prev;
WGraph(ll n) : n{n}, adj(n+1) {}
void addEdge(ll s, ll e, ll cost) {
adj[s].push_back({e, cost});
}
void input(ll m) { // 단방향
ll a, b, c;
while(m--) {
cin >> a >> b >> c;
addEdge(a,b,c);
}
}
void inputD(ll m) { // 양방향
ll a, b, c;
while(m--){
cin >> a >> b >> c;
addEdge(a,b,c);
addEdge(b,a,c);
}
}
vector <ll> dijkstra(ll s) {
vector <ll> dist(n+1, INF);
prev.resize(n+1, -1);
priority_queue<edge> pq;
pq.push({ s, 0ll });
dist[s] = 0;
while (!pq.empty()) {
edge cur = pq.top();
pq.pop();
if (cur.cost > dist[cur.node]) continue;
for (auto &nxt : adj[cur.node])
if (dist[cur.node] + nxt.cost < dist[nxt.node]) {
prev[nxt.node] = cur.node;
dist[nxt.node] = dist[cur.node] + nxt.cost;
pq.push({ nxt.node, dist[nxt.node] });
}
}
return dist;
}
vector<ll> getPath(ll s, ll e) {
vector<ll> ret;
ll current = e;
while(current != -1) {
ret.push_back(current);
current = prev[current];
}
reverse(ret.begin(), ret.end());
return ret;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
ll v, e, start;
cin >> v >> e;
cin >> start;
WGraph w(v);
w.input(e);
vector<ll> ret = w.dijkstra(start);
for1(1, v+1) {
if(ret[i] == INF) cout <<"INF\n";
else cout << ret[i] <<"\n";
}
}