[BOJ] 1916๋ฒ | ์ต์๋น์ฉ ๊ตฌํ๊ธฐ (C++)
2023. 12. 13. 18:45ใCoding Test/BOJ
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐ง๐ปํ์ด ๊ณผ์
์ผ๋ง ์ ์ ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ(Dijkstra Algorithm)์ ๊ณต๋ถํ์์ผ๋, ๋จธ๋ฆฟ ์์์ ์ธ์ถํ๋ ์ฐ์ต์ ์ํด ๋น์ทํ ์ ํ์ ๋ฌธ์ ๋ฅผ ํ๋ ํ์ด๋ดค์ต๋๋ค. ์ฐ๋ฆฌ ๋ง์ด ์ด๋ ค์ด ๊ฑด์ง, ์ ๊ฐ ๋ฉ์ฒญํ ๊ฑด์ง ๋ชจ๋ฅด๊ฒ ์ง๋ง ๋งค๋ฒ ํท๊ฐ๋ฆฌ๋ ๊ฒ ๊ฐ์์... ๊ทธ๋์ ์ฐ์ต์ฅ์ ๊ทธ๋ฆผ ๊ทธ๋ ค๊ฐ๋ฉฐ ํ๋๋ค. ( "distances[v] vs distances[u] + nextCost" ๐๐ป ์ด๊ฒ ์ ค ํท๊ฐ๋ฆฝ๋๋ค. )
์๊ณ ๋ฆฌ์ฆ์ ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ ๊ทธ ์์ฒด์ด๋, ๐[BOJ] 13549๋ฒ | ์จ๋ฐ๊ผญ์ง 3 ์ ์ ์๋ ํ์ด ๊ทธ๋๋ก ์ ์ฉํ๋ฉด ๋ฉ๋๋ค.
โ๏ธ ์์ค ์ฝ๋ ๋ฐ ๊ฒฐ๊ณผ
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
using uint32 = unsigned int;
using Route = pair<uint32, uint32>;
#define FAST_IO ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL);
#define INF 4000000000
void Dijkstra(const vector<vector<Route>>& routes, vector<uint32>& distances, uint32 start) {
priority_queue<Route, vector<Route>, greater<Route>> buses;
distances[start] = 0;
buses.emplace(0, start);
while (!buses.empty()) {
Route bus = buses.top();
uint32 nextCityCost = bus.first;
uint32 nextCity = bus.second;
buses.pop();
if (distances[nextCity] < nextCityCost)
continue;
for (const auto& route : routes[nextCity]) {
uint32 newCityCost = route.first;
uint32 newCity = route.second;
uint32 newPathCost = distances[nextCity] + newCityCost;
if (newPathCost < distances[newCity]) {
distances[newCity] = newPathCost ;
buses.emplace(newPathCost, newCity);
}
}
}
}
int main() {
FAST_IO
int N, M;
cin >> N >> M;
uint32 from, to, cost;
vector<vector<Route>> busRouteInfo(N + 1, vector<Route>());
for (int i = 0; i < M; i++) {
cin >> from >> to >> cost;
busRouteInfo[from].emplace_back(cost, to);
}
vector<uint32> distances(N + 1, INF);
uint32 start, destination;
cin >> start >> destination;
Dijkstra(busRouteInfo, distances, start);
cout << distances[destination];
return 0;
}
728x90
๋ฐ์ํ
'Coding Test > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] 1766๋ฒ | ๋ฌธ์ ์ง (C++) (0) | 2023.12.19 |
---|---|
[BOJ] 1074๋ฒ | Z (C++) (0) | 2023.12.18 |
[BOJ] 1987๋ฒ | ์ํ๋ฒณ (C++) (0) | 2023.12.13 |
[BOJ] 14502๋ฒ | ์ฐ๊ตฌ์ (C++) (0) | 2023.12.13 |
[BOJ] 17472๋ฒ | ๋ค๋ฆฌ ๋ง๋ค๊ธฐ 2 (C++) (0) | 2023.12.12 |