1916번: 최소비용 구하기
첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그
www.acmicpc.net
다익스트라 알고리즘을 이용하는 문제였다.
입력으로 주어지는 버스의 정보를 간선으로 연결하고, 출발 도시를 시작 정점으로 하는 다익스트라 알고리즘을 수행하면 출발 도시에서 모든 도시로 가는 최소 비용을 구할 수 있다. 여기서 도착 도시로 가는 최소 비용을 찾아 출력해주면 원하는 결과를 얻을 수 있다.
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int INF = 987654321;
int N, M;
vector<pair<int, int>> adj[1001];
int dijkstra(int start, int arrive){
vector<int> dist(N+1, INF);
dist[start] = 0;
priority_queue<pair<int, int>> pq;
pq.push({ 0, start });
while (!pq.empty()) {
int here = pq.top().second;
int cost = -pq.top().first;
pq.pop();
if (dist[here] < cost) continue;
for (int i = 0; i < adj[here].size(); i++) {
int there = adj[here][i].first;
int nextCost = adj[here][i].second + cost;
if (dist[there] > nextCost) {
dist[there] = nextCost;
pq.push({ -nextCost, there });
}
}
}
return dist[arrive];
}
int main(void) {
cin >> N >> M;
for (int i = 0; i < M; i++) {
int s, e, w;
cin >> s >> e >> w;
adj[s].push_back({ e, w });
}
int start, arrive;
cin >> start >> arrive;
cout << dijkstra(start, arrive) << endl;
return 0;
}

알고리즘 200일 프로젝트 - 164 day
'알고리즘 > BOJ' 카테고리의 다른 글
백준 1389번: 케빈 베이컨의 6단계 법칙 (0) | 2020.09.20 |
---|---|
백준 1707번: 이분 그래프 (0) | 2020.09.20 |
백준 1922번: 네트워크 연결 (0) | 2020.09.20 |
백준 1197번: 최소 스패닝 트리 (0) | 2020.09.19 |
백준 2252번: 줄 세우기 (0) | 2020.09.19 |