되면한다
백준 1916. 최소비용 구하기 (다익스트라) 본문
https://www.acmicpc.net/problem/1916
1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
1. 특징
1) 우선순위큐를 이용한 다익스트라
2. 구현방식
1) 출발도시(정점)별 <비용, 도착도시>를 설정함.
vector<pair<int, int>> adj[1004]; //비용, 도착도시 (출발도시별)
2) 정점까지 오는 최단 거리를 나타내는 배열을 선언하고, MAX값으로 초기화함.
int d[1004];
fill(d, d + n + 1, INT_MAX);
3) 우선순위 큐를 이용한 다익스트라 알고리즘

이미지출처: 바킹독의 실전 알고리즘 0xID강 - 다익스트라 알고리즘
3. 코드
#include <iostream>
#include <vector>
#include <queue>
#include <limits.h>
using namespace std;
int n, m;
int u, v, w;
int st, en;
vector<pair<int, int>> adj[1004]; //비용, 도착도시 (출발도시별)
int d[1004];
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
fill(d, d + n + 1, INT_MAX);
for(int i = 0; i < m; i++)
{
cin >> u >> v >> w;
adj[u].push_back(make_pair(w, v));
}
cin >> st >> en;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; //최소값 출력하는 우선순위 큐
d[st] = 0;
pq.push(make_pair(0, st));
while(!pq.empty())
{
auto cur = pq.top(); pq.pop();
if(cur.first != d[cur.second]) continue;
for(auto nxt:adj[cur.second])
{
if(d[nxt.second] <= d[cur.second] + nxt.first) continue;
d[nxt.second] = d[cur.second] + nxt.first;
pq.push(make_pair(d[nxt.second], nxt.second));
}
}
cout << d[en];
}
'코딩테스트준비' 카테고리의 다른 글
백준 16113. 시그널(bfs) (0) | 2023.08.23 |
---|---|
백준 1541. 잃어버린 괄호 (그리디) (0) | 2023.08.17 |
백준 1238. 파티 (다익스트라) (0) | 2023.08.14 |
백준 3107. IPv6 (문자열) (0) | 2023.08.13 |
백준 1991. 트리 순회(전위, 중위, 후위 순회) (0) | 2023.07.31 |
Comments