Skip to content

Commit 671f5e8

Browse files
authored
Create [16]_2.cpp
1 parent 498a070 commit 671f5e8

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

Solutions/[16]_2.cpp

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
int n, m, start, finish;
6+
vector<pair<int, int> > adj[500];
7+
int d[500];
8+
vector<pair<int, int> > reverseAdj[500];
9+
bool dropped[500][500];
10+
11+
void dijkstra() {
12+
priority_queue<pair<int, int> > pq;
13+
pq.push(make_pair(0, start));
14+
d[start] = 0;
15+
while (!pq.empty()) {
16+
int dist = -pq.top().first; // 현재 노드까지의 비용
17+
int now = pq.top().second; // 현재 노드
18+
pq.pop();
19+
if (d[now] < dist) continue;
20+
for (int i = 0; i < adj[now].size(); i++) {
21+
int next = adj[now][i].first; // 다음 노드
22+
int nextDist = dist + adj[now][i].second; // 현재 노드를 거쳐 가는 비용
23+
if (d[next] > nextDist && !dropped[now][next]) {
24+
d[next] = nextDist;
25+
pq.push(make_pair(-nextDist, next));
26+
}
27+
}
28+
}
29+
}
30+
31+
void bfs() {
32+
queue<int> q;
33+
q.push(finish);
34+
while (!q.empty()) {
35+
int now = q.front();
36+
q.pop();
37+
if (now == start) continue;
38+
for (int i = 0; i < reverseAdj[now].size(); i++) {
39+
int prev = reverseAdj[now][i].first;
40+
int cost = reverseAdj[now][i].second;
41+
// 최단 경로에 포함된 경우 체크하기
42+
if (d[now] == d[prev] + cost) {
43+
dropped[prev][now] = true;
44+
q.push(prev);
45+
}
46+
}
47+
}
48+
}
49+
50+
int main() {
51+
while (true) {
52+
cin >> n >> m;
53+
if (n == 0) break;
54+
cin >> start >> finish;
55+
for (int i = 0; i < n; i++) {
56+
adj[i].clear();
57+
reverseAdj[i].clear();
58+
}
59+
for (int i = 0; i < m; i++) {
60+
int x, y, cost;
61+
cin >> x >> y >> cost;
62+
adj[x].push_back(make_pair(y, cost));
63+
reverseAdj[y].push_back(make_pair(x, cost));
64+
}
65+
// false로 초기화할 때는 memset() 함수 이용
66+
memset(dropped, false, sizeof(dropped));
67+
// 특정한 값으로 초기화할 때는 fill() 함수 이용
68+
fill(d, d + 500, 1e9);
69+
dijkstra();
70+
bfs();
71+
fill(d, d + 500, 1e9);
72+
dijkstra();
73+
if (d[finish] != 1e9) {
74+
cout << d[finish] << '\n';
75+
}
76+
else {
77+
cout << -1 << '\n';
78+
}
79+
}
80+
}

0 commit comments

Comments
 (0)