3 min read

๊ทธ๋ž˜ํ”„ ์ตœ๋‹จ๊ฒฝ๋กœ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ •๋ฆฌ

Table of Contents

๋‹ค์ต์ŠคํŠธ๋ผ (Dijkstra)

์‹œ์ž‘ ์ •์ ์—์„œ, ๋‹ค๋ฅธ ๋ชจ๋“  ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ O(ElogโกV)O(E\log V)์— ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ชจ๋“  ๊ฐ„์„ ์„ ํ•œ ๋ฒˆ์”ฉ ํ™•์ธํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„. ์ตœ๋‹จ๊ฑฐ๋ฆฌ๊ฐ€ ์—ฌ๋Ÿฌ ๋ฒˆ ๊ฐฑ์‹ ๋œ ๊ฒฝ์šฐ (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)

์‹œ์ž‘ ์ •์ ์—์„œ, ๋‹ค๋ฅธ ๋ชจ๋“  ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ O(EV)O(EV)์— ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค. ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜๊ณผ๋Š” ๋‹ฌ๋ฆฌ ์Œ์˜ ๊ฐ„์„ ์ด ์กด์žฌํ•ด๋„ ์ฃผ์–ด์ง„ ์‹œ๊ฐ„ ์•ˆ์— ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค. ์ตœ๋‹จ๊ฒฝ๋กœ๋Š” ์•„๋ฌด๋ฆฌ ๊ธธ์–ด๋„ Vโˆ’1V-1๊ฐœ์˜ ๊ฐ„์„ ์„ ํฌํ•จํ•˜๊ณ  ์žˆ์„ ๊ฒƒ์ด๋‹ค. ๋”ฐ๋ผ์„œ ๊ฐ„์„  ์™„ํ™”๋ฅผ Vโˆ’1V-1๋ฒˆ ์ง„ํ–‰ํ•œ๋‹ค. ๋งŒ์•ฝ Vโˆ’1V-1๋ฒˆ ์ง„ํ–‰ ์ดํ›„์—๋„ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๊ฐ€ ์งง์•„์ง„๋‹ค๋ฉด, ์ด๋Š” ์Œ์˜ ์‚ฌ์ดํด์„ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๊ฒƒ์ด๋‹ค.

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)

๋ชจ๋“  ์ •์ ์—์„œ, ๋‹ค๋ฅธ ๋ชจ๋“  ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ O(N3)O(N^3) ์— ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ฐ˜๋ณต๋ฌธ ์ˆœ์„œ์— ์œ ์˜ํ•œ๋‹ค. dist(i,j)dist(i, j)์™€ dist(i,k)+dist(k,j)dist(i, k) + dist(k, j)๋ฅผ ๋น„๊ตํ•˜๋Š”๋ฐ, kk๋ฅผ ๊ณ ์ •์‹œ์ผœ๋†“๊ณ  i,ji, j๋ฅผ ์›€์ง์ธ๋‹ค. ๋‹ค์ด๋‚˜๋ฏน ํ”„๋กœ๊ทธ๋ž˜๋ฐ์˜ ์ผ์ข….

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]);
		}
	}
}