본문 바로가기
Solved.ac/Class 4

[BOJ] 백준 11779번: 최소비용 구하기 2

by 강성주의 알고리즘 2020. 6. 19.

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <memory.h>
#include <math.h>

using namespace std;
typedef pair<int, int> pii;
typedef long long ll;
vector<pii> v[1001];
int dist[1001];
int pre[1001];
int n, m;
int s, e;
int main() {
	
	ios_base::sync_with_stdio(false);
	cin.tie(NULL), cout.tie(NULL);
	cin >> n >> m;
	memset(pre, -1, sizeof(pre));
	for (int i = 1; i <= n; i++) {
		dist[i] = 2e9;
	}
	for (int i = 0; i < m; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		v[a].push_back({ b,c });
	}
	cin >> s >> e;
	priority_queue<pii, vector<pii> > pq;
	dist[s] = 0;
	pq.push({ 0,s });
	while (!pq.empty()) {
		int node = pq.top().second;
		pq.pop();

		for (auto nxt : v[node]) {
			int next = nxt.first;
			int cost = nxt.second;
			
			if (dist[next] > dist[node] + cost) {
				dist[next] = dist[node] + cost;
				pre[next] = node;
				pq.push({ -dist[next],next });
			}
		}
	}
	stack<int> path;
	for (int i = e; i != -1; i = pre[i]) {
		path.push(i);
	}
	cout << dist[e] << "\n";
	cout << path.size() << "\n";
	while (!path.empty()) {
		cout << path.top() << " ";
		path.pop();
	}

	
}
반응형

'Solved.ac > Class 4' 카테고리의 다른 글

[BOJ] 백준 1865번: 웜홀  (0) 2020.06.19
[BOJ] 백준 14938번: 서강그라운드  (0) 2020.06.19
[BOJ] 백준 1238번: 파티  (0) 2020.06.19
[BOJ]백준 1167번: 트리의 지름  (0) 2020.06.19
[BOJ] 백준 1016번: 제곱ㄴㄴ수  (0) 2020.06.19