forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2.cpp
66 lines (58 loc) Β· 2.27 KB
/
2.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
#include <bits/stdc++.h>
#define INF 1e9 // 무νμ μλ―Ένλ κ°μΌλ‘ 10μ΅μ μ€μ
using namespace std;
// λ
Έλμ κ°μ(N), κ°μ μ κ°μ(M), μμ λ
Έλ λ²νΈ(Start)
// λ
Έλμ κ°μλ μ΅λ 100,000κ°λΌκ³ κ°μ
int n, m, start;
// κ° λ
Έλμ μ°κ²°λμ΄ μλ λ
Έλμ λν μ 보λ₯Ό λ΄λ λ°°μ΄
vector<pair<int, int> > graph[100001];
// μ΅λ¨ 거리 ν
μ΄λΈ λ§λ€κΈ°
int d[100001];
void dijkstra(int start) {
priority_queue<pair<int, int> > pq;
// μμ λ
Έλλ‘ κ°κΈ° μν μ΅λ¨ κ²½λ‘λ 0μΌλ‘ μ€μ νμ¬, νμ μ½μ
pq.push({0, start});
d[start] = 0;
while (!pq.empty()) { // νκ° λΉμ΄μμ§ μλ€λ©΄
// κ°μ₯ μ΅λ¨ κ±°λ¦¬κ° μ§§μ λ
Έλμ λν μ 보 κΊΌλ΄κΈ°
int dist = -pq.top().first; // νμ¬ λ
ΈλκΉμ§μ λΉμ©
int now = pq.top().second; // νμ¬ λ
Έλ
pq.pop();
// νμ¬ λ
Έλκ° μ΄λ―Έ μ²λ¦¬λ μ μ΄ μλ λ
ΈλλΌλ©΄ 무μ
if (d[now] < dist) continue;
// νμ¬ λ
Έλμ μ°κ²°λ λ€λ₯Έ μΈμ ν λ
Έλλ€μ νμΈ
for (int i = 0; i < graph[now].size(); i++) {
int cost = dist + graph[now][i].second;
// νμ¬ λ
Έλλ₯Ό κ±°μ³μ, λ€λ₯Έ λ
Έλλ‘ μ΄λνλ κ±°λ¦¬κ° λ 짧μ κ²½μ°
if (cost < d[graph[now][i].first]) {
d[graph[now][i].first] = cost;
pq.push(make_pair(-cost, graph[now][i].first));
}
}
}
}
int main(void) {
cin >> n >> m >> start;
// λͺ¨λ κ°μ μ 보λ₯Ό μ
λ ₯λ°κΈ°
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
// aλ² λ
Έλμμ bλ² λ
Έλλ‘ κ°λ λΉμ©μ΄ cλΌλ μλ―Έ
graph[a].push_back({b, c});
}
// μ΅λ¨ 거리 ν
μ΄λΈμ λͺ¨λ 무νμΌλ‘ μ΄κΈ°ν
fill(d, d + 100001, INF);
// λ€μ΅μ€νΈλΌ μκ³ λ¦¬μ¦μ μν
dijkstra(start);
// λͺ¨λ λ
Έλλ‘ κ°κΈ° μν μ΅λ¨ 거리λ₯Ό μΆλ ₯
for (int i = 1; i <= n; i++) {
// λλ¬ν μ μλ κ²½μ°, 무ν(INFINITY)μ΄λΌκ³ μΆλ ₯
if (d[i] == INF) {
cout << "INFINITY" << '\n';
}
// λλ¬ν μ μλ κ²½μ° κ±°λ¦¬λ₯Ό μΆλ ₯
else {
cout << d[i] << '\n';
}
}
}