[백준 BOJ 1916] 최소비용 구하기

2020. 2. 17. 16:14BOJ

반응형

백준 링크

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

풀이

  • 우선순위 큐(힙)을 사용한 다익스트라를 이용해 O(ElogV)로 풀 수 있었다
  • 다익스트라:

코드

#include<iostream>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;

struct Edge {
	int to, cost;
};
vector<vector<Edge>> edge(1005);
int n, m, s, e, dist[1005];
bool c[1005];

void dijkstra() {
	priority_queue<pair<int, int>> pq;
	dist[s] = 0;
	pq.push(make_pair(0, s));
	while(!pq.empty()) {
		pair<int,int> cur = pq.top();
		pq.pop();
		int size = edge[cur.second].size(), from = cur.second;
		if (c[from]) continue;
		c[from] = true;
		for (int j = 0; j < size; j++) {
			int to = edge[from][j].to, cost = edge[from][j].cost;
			if (dist[to] > dist[from] + cost)
				dist[to] = dist[from] + cost;
			pq.push(make_pair(-dist[to], to));
		}
	}
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		dist[i] = 987654321;
	}
	int cost;
	for (int i = 0; i < m; i++) {
		cin >> s >> e >> cost;
		edge[s].push_back({ e, cost });
	}
	cin >> s >> e;
	dijkstra();
	cout << dist[e];
}
반응형

'BOJ' 카테고리의 다른 글

[백준 BOJ 10868] 최솟값  (0) 2020.02.21
[백준 BOJ 1766] 문제집  (0) 2020.02.19
[백준 BOJ 2294] 동전 2  (0) 2020.02.14
[백준 BOJ 9012] 괄호  (2) 2020.02.14