www.acmicpc.net/problem/1916

 

1916번: 최소비용 구하기

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

www.acmicpc.net

그냥 단순한 다익스트라 알고리즘을 사용한 문제였다.

 

최근 본 코테에서 다익스트라가 나왔는데도 불구하고 생각이 안나 못풀었던 걸 생각하면ㅠㅠ 미리 왜 공부를 안했나 후회가 되는 문제였다.

 

참고 블로그: alswnsdl.tistory.com/13

 

다익스트라 알고리즘(Dijkstra's algorithm) C++ 코드

다익스트라 알고리즘의 개념은 이전 게시물 http://alswnsdl.tistory.com/12 을 참고 하시면 됩니다. 이번에는 다익스트라 알고리즘의 소스코드에 대해 적어보겠습니다. 다익스트라의 소스코드는 두가

alswnsdl.tistory.com

이 블로그를 통해 우선순위를 이용한 다익스트라 알고리즘을 공부하였고 문제에 적용할 수 있었다.

 

#define _CRT_SECURE_NO_WARNINGS
#define INF 1e9
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int main() {
	int V, E, start, end;
	int a, b, c;
	cin >> V >> E;
	vector<pair<int, int>> arr[1001];
	int dist[1001];

	for (int i = 0; i < E; i++) {
		cin >> a >> b >> c;
		arr[a].push_back({ b,c });
	}
	cin >> start >> end;
	fill(dist, dist + V + 1, INF);
	priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;

	pq.push({ 0, start});
	dist[start] = 0;

	while (!pq.empty()) {
		int cost = pq.top().first;
		int here = pq.top().second;
		pq.pop();

		for (int i = 0; i < arr[here].size(); i++) {
			int next = arr[here][i].first;
			int ncost = arr[here][i].second;

			if (dist[next] > dist[here] + ncost) {
				dist[next] = dist[here] + ncost;
				pq.push({ dist[next], next });
			}
		}
	}
	cout << dist[end];
	return 0;
}

+ Recent posts