๋ฌธ์ :
๋ถ์ :
์ด๋ฒ ๋ฌธ์ ๋ ์ ๋ฌธ์ 1916๋ฒ
2021.03.10 - [Algorithm๐ฐ/๋ฐฑ์ค] - [๋ฐฑ์ค] 1916 ์ต์๋น์ฉ ๊ตฌํ๊ธฐ dijkstra
์ ๊ฑฐ์ณ๊ฐ ๋ ธ๋๋ฅผ ์ถ๋ ฅํ ์ ์๋๋ก ์ถ๊ฐํ๋ ์์ ์ด ํ์ํ๋ค.
๋ฐ๋ผ์ while ๋ฌธ ์ for ๋ฌธ์ t ๋ฐฐ์ด์ ํ๋ ์ถ๊ฐํด ๊ทธ ์ ๋ ธ๋๋ฅผ ์ธ๋ฑ์ค ๊ฐ์ผ๋ก ํ์ฌ ๋ ธ๋์ ๊ฐ์ ๋ฃ์ด์ฃผ๊ณ
๊ทธ ์ popํด์จ ๋ ธ๋(now)๋ฅผ ๊ฐ์ผ๋ก ๋ฐ๋๋ก ํ์๋ค.
์ถ๋ ฅํ ๋์๋ end์ธ๋ฑ์ค๋ถํฐ route ๋ฒกํฐ์ ๋ด๊ธด๋ค. ๊ทธ๋์ ์ญ์์ผ๋ก ๋ฒกํฐ๋ฅผ ์ถ๋ ฅํด๋๋ก ํ์๋ค,
c++ ์ฝ๋ :
//
// 11779_min_cost2.cpp
// SOMA๐ฉ๐ป๐ป
//
// Created by JoSoJeong on 2021/03/10.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define INF 1e9
vector<pair<int, int>>vertex[1001];
int d[100001]; // ์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ
int t[100001];
void min_bus(int start, int end){
priority_queue<pair<int, int>>pq;
pq.push(make_pair(0, start));
d[start] = 0;
while(!pq.empty()){
int dist = -pq.top().first;
int now = pq.top().second;
pq.pop();
for(int i = 0; i < vertex[now].size(); i++){
int cost = dist + vertex[now][i].second;
if(cost < d[vertex[now][i].first]) // ๋น์ฉ์ด ๋ ์๋ค๋ฉด ์ต๋จ๊ฒฝ๋ก ํ
์ด๋ธ ๊ฐ์ ๊ฐฑ์ .
{
d[vertex[now][i].first] = cost;
t[vertex[now][i].first] = now; // ์ ๋
ธ๋๊ฐ ๋ถ๋ชจ ๋
ธ๋ ๊ฐ์ง๊ณ ์๋๋ก
pq.push(make_pair(-cost,vertex[now][i].first));
}
}
}
}
int main(){
int city;
cin >> city;
int bus;
cin >> bus;
for(int i = 0 ; i < bus; i++){
int in, to, cost;
cin >> in >> to >> cost;
vertex[in].push_back({to, cost});
}
int start, end;
cin >> start >> end;
fill(d, d+100001, INF);
min_bus(start, end);
cout << d[end] << '\n';
vector<int>route;
int temp_end = end;
while (temp_end)
{
route.push_back(temp_end);
temp_end = t[temp_end];
}
cout << route.size() << endl;
for (int i = ((int)route.size()) - 1; i >= 0; i--) cout << route[i] << " ";
cout << endl;
return 0;
}
'Algorithm๐ฐ > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] ์น์ฆ 2636 bfs (0) | 2021.04.02 |
---|---|
[๋ฐฑ์ค] 14502 ์ฐ๊ตฌ์ bfs (0) | 2021.04.01 |
[๋ฐฑ์ค] 1916 ์ต์๋น์ฉ ๊ตฌํ๊ธฐ dijkstra (0) | 2021.03.10 |
[๋ฐฑ์ค] 1753 ์ต๋จ ๊ฒฝ๋ก dijkstra (0) | 2021.03.10 |
[๋ฐฑ์ค] 12865 ํ๋ฒํ ๋ฐฐ๋ญ knapsack ์๊ณ ๋ฆฌ์ฆ (0) | 2021.03.09 |
๋๊ธ