[ 문제 ]
11779번: 최소비용 구하기 2
첫째 줄에 도시의 개수 n(1≤n≤1,000)이 주어지고 둘째 줄에는 버스의 개수 m(1≤m≤100,000)이 주어진다. 그리고 셋째 줄부터 m+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그 버스
www.acmicpc.net
[ 접근방법 ]
노드 사이의 거리가 음수가 아니기에 다익스트라 알고리즘을 사용할 수 있다.
다익스트라는 최단거리가 확정된 노드를 찾는 부분을 우선순위 큐를 통해 고속화 할 수 있다.
따라서 O( E logV ) 만에 문제를 해결할 수 있다.
[ 소스코드 ]
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
typedef pair<int, int> P;
int n, m, a, b, c;
int INF = 100000000;
vector<P> edge[1010];
int d[1010], past[1010];
vector<int> path;
priority_queue<P, vector<P>, greater<P>> pq;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < m; i++)
{
cin >> a >> b >> c;
edge[a].push_back(P(b, c));
}
cin >> a >> b;
for (int i = 1; i <= n; i++)
d[i] = INF;
d[a] = 0;
pq.push(P(0, a));
while (!pq.empty())
{
P p = pq.top();
pq.pop();
if (d[p.second] < p.first)
continue;
for (auto i : edge[p.second])
{
if (d[i.first] > d[p.second] + i.second)
{
d[i.first] = d[p.second] + i.second;
pq.push(P(d[i.first], i.first));
past[i.first] = p.second;
}
}
}
cout << d[b] << "\n";
for (int i = b; i > 0; i = past[i])
path.push_back(i);
reverse(path.begin(), path.end());
cout << path.size() << "\n";
for (auto i : path)
cout << i << " ";
return 0;
}
'PS' 카테고리의 다른 글
[ 백준 / C++ ] 15686 : 치킨 배달 (0) | 2024.04.26 |
---|---|
[ 백준 / C++ ] 14940 : 쉬운 최단거리 (0) | 2024.04.25 |
[ 백준 / C++ ] 1915 : 가장 큰 정사각형 (0) | 2024.04.23 |
[ 백준 / C++ ] 8979 : 올림픽 (0) | 2024.04.22 |
[ 백준 / C++ ] 1202 : 보석 도둑 (0) | 2024.04.19 |