๋ค์ต์คํธ๋ผ (Dijkstra)
์์ ์ ์ ์์, ๋ค๋ฅธ ๋ชจ๋ ์ ์ ๊น์ง์ ์ต๋จ๊ฑฐ๋ฆฌ๋ฅผ ์ ๊ตฌํ ์ ์๋ค. ๋ชจ๋ ๊ฐ์ ์ ํ ๋ฒ์ฉ ํ์ธํ๊ธฐ ๋๋ฌธ์ ์ธ์ ๋ฆฌ์คํธ๋ก ๊ตฌํ. ์ต๋จ๊ฑฐ๋ฆฌ๊ฐ ์ฌ๋ฌ ๋ฒ ๊ฐฑ์ ๋ ๊ฒฝ์ฐ (cost > dist[cur]) ์คํต. cost๊ฐ ๋ฎ์ ๊ฐ์ ๋ถํฐ ํ์ธ.
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
int dijkstra(int start, int end) {
fill(dist, dist+MAX, INF);
dist[start] = 0;
pq.emplace(0, start);
while (!pq.empty()) {
auto [cost, cur] = pq.top();
pq.pop();
if (cost > dist[cur]) continue;
for (auto& [ncost, next] : adj[cur]) {
if (dist[next] > dist[cur] + ncost) {
dist[next] = dist[cur] + ncost;
pq.emplace(dist[next], next);
}
}
}
return dist[end];
}
๋ฒจ๋ง ํฌ๋ (Bellman - Ford)
์์ ์ ์ ์์, ๋ค๋ฅธ ๋ชจ๋ ์ ์ ๊น์ง์ ์ต๋จ๊ฑฐ๋ฆฌ๋ฅผ ์ ๊ตฌํ ์ ์๋ค. ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ๊ณผ๋ ๋ฌ๋ฆฌ ์์ ๊ฐ์ ์ด ์กด์ฌํด๋ ์ฃผ์ด์ง ์๊ฐ ์์ ์ต๋จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ ์ ์๋ค. ์ต๋จ๊ฒฝ๋ก๋ ์๋ฌด๋ฆฌ ๊ธธ์ด๋ ๊ฐ์ ๊ฐ์ ์ ํฌํจํ๊ณ ์์ ๊ฒ์ด๋ค. ๋ฐ๋ผ์ ๊ฐ์ ์ํ๋ฅผ ๋ฒ ์งํํ๋ค. ๋ง์ฝ ๋ฒ ์งํ ์ดํ์๋ ์ต๋จ๊ฑฐ๋ฆฌ๊ฐ ์งง์์ง๋ค๋ฉด, ์ด๋ ์์ ์ฌ์ดํด์ ๊ฐ์ง๊ณ ์๋ ๊ฒ์ด๋ค.
int start = 0;
fill(dist, dist+MAX, INF);
dist[start] = 0;
bool neg = false;
for (int k = 0; k < N; k++) {
for (int i = 0; i < N; i++) {
if (dist[i] == INF) continue;
for (auto p : adj[i]) {
auto [cost, next] = p;
if (dist[next] > dist[i] + cost) {
dist[next] = dist[i] + cost;
if (k == N-1) neg = true;
}
}
}
}
ํ๋ก์ด๋ ์์ฌ (Floyd - Warshall)
๋ชจ๋ ์ ์ ์์, ๋ค๋ฅธ ๋ชจ๋ ์ ์ ๊น์ง์ ์ต๋จ๊ฑฐ๋ฆฌ๋ฅผ ์ ๊ตฌํ ์ ์๋ค. ๋ฐ๋ณต๋ฌธ ์์์ ์ ์ํ๋ค. ์ ๋ฅผ ๋น๊ตํ๋๋ฐ, ๋ฅผ ๊ณ ์ ์์ผ๋๊ณ ๋ฅผ ์์ง์ธ๋ค. ๋ค์ด๋๋ฏน ํ๋ก๊ทธ๋๋ฐ์ ์ผ์ข .
while (r--) {
int a, b, c;
cin >> a >> b >> c;
dist[a-1][b-1] = c;
dist[b-1][a-1] = c;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (!dist[i][j]) dist[i][j] = 1e9;
if (i == j) dist[i][j] = 0;
}
}
// i -> j vs i -> k -> j
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}