본문 바로가기

Algorithm/BAEKJOON

[BOJ] 1916번 최소비용 구하기 (C++)

728x90
반응형

https://www.acmicpc.net/problem/1916

 

1916번: 최소비용 구하기

첫째 줄에 도시의 개수 N(1 ≤ N ≤ 1,000)이 주어지고 둘째 줄에는 버스의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 그리고 셋째 줄부터 M+2줄까지 다음과 같은 버스의 정보가 주어진다. 먼저 처음에는 그

www.acmicpc.net

 

#include <iostream>
#include <queue>
#include <vector>
#define INF 987654321;
using namespace std;

int dist[1001];
vector<pair<int, int>> v[100001];

void dijkstra(int start){
	dist[start] = 0;
	priority_queue<pair<int, int>> pq;
	pq.push({dist[start], start});
	
	while(!pq.empty()){
		int cur = pq.top().second;
		int distance = pq.top().first * -1;
		pq.pop();
		
		if(dist[cur] < distance) continue;
		
		for(int i = 0; i < v[cur].size(); i++){
			int next = v[cur][i].first;
			int nextDistance = distance + v[cur][i].second;
			
			if(nextDistance < dist[next]){
				dist[next] = nextDistance;
				pq.push({nextDistance * -1, next});
			}
		}
	}
}


int main(){
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	int n, m, start, end;
	cin >> n >> m;
	
	for(int i = 1; i <= n; i++) dist[i] = INF;
	for(int i = 0; i < m; i++){
		int from, to, cost;
		cin >> from >> to >> cost;
		v[from].push_back({to, cost});
	}
	cin >> start >> end;
	
	dijkstra(start);
	
	cout << dist[end] << endl;
}
728x90
반응형

'Algorithm > BAEKJOON' 카테고리의 다른 글

[BOJ] 1918번 후위 표기식 (C++)  (0) 2022.05.07
[BOJ] 9251번 LCS (C++)  (0) 2022.05.06
[BOJ] 1240번 노드사이의 거리 (C++)  (0) 2022.05.05
[BOJ] 1719번 택배 (C++)  (0) 2022.05.05
[BOJ] 11404번 플로이드 (C++)  (0) 2022.05.04