Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

uos-machine-learning

11779 - 최소비용 구하기 본문

알고리즘/문제풀이

11779 - 최소비용 구하기

이산한하루 2019. 5. 11. 22:58

다익스트라에서 dist 배열을 갱신할 때 마다 parent 배열에 연결된 노드를 저장하면 된다.

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#define INF 0x7fffffff;
using namespace std;

vector<pair<int, int>> adj[1001];
// 최소 비용 저장
int dist[1001];
// 최소 비용을 갖는 부모 저장
int parent[1001];
// 경로에 포함된 도시 경로 개수
int cnt;
bool visited[1001];
void dijkstra(int root) {
	dist[root] = 0;
	priority_queue<pair<int, int>> q;
	q.push({ 0, root });
	while (!q.empty()) {
		int now = q.top().second; q.pop();
		if (visited[now]) continue;
		visited[now] = true;
		for (auto p : adj[now]) {
			int next = p.first;
			int w = p.second;
			if (w + dist[now] < dist[next]) {
				dist[next] = w + dist[now];
				parent[next] = now;
				cnt++;
				q.push({ -dist[next], next });
			}
		}
	}
}
int main()
{
	int N, M;
	cin >> N >> M;
	int s, e;
	for (int i = 1; i <= N; i++) {
		dist[i] = INF;
	}
	for (int m = 0; m < M; m++) {
		int u, v, x;
		cin >> u >> v >> x;
		adj[u].push_back({ v, x });
	}
	cin >> s >> e;
	dijkstra(s);
	printf("%d\n", dist[e]);
	stack<int> st;
	while (e != 0) {
		st.push(e);
		e = parent[e];
	}
	printf("%d\n", st.size());
	while (!st.empty()) {
		printf("%d ", st.top());
		st.pop();
	}
}

'알고리즘 > 문제풀이' 카테고리의 다른 글

11403 - 경로 찾기  (0) 2019.05.11
1956 - 운동  (0) 2019.05.11
1916 - 최소비용 구하기  (0) 2019.05.10
1197 - 최소 스패닝 트리  (0) 2019.05.10
1922 - 네트워크 연결  (0) 2019.05.09
Comments