Posts 11779 최소비용구하기 2
Post
Cancel

11779 최소비용구하기 2

알고리즘

  • 일반적인 다익스트라로 푸는데, 풀면서 이전에 어디서 왔는지를 기록한다.
  • 다익스트라가 끝나고, 끝에서부터 왔던길을 되돌아가며 경로를 찾아낸다.

코드

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
#define INF 2000000000000

typedef long long ll;
using namespace std;

int n, m, s, e, path[1001];
vector<int> p;
vector<pair<int, int>> to[1001];
priority_queue<pair<ll, int>> q;
ll cost[1001];

void dijkstra();
void checkPath();

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> n >> m;
	while (m--) {
		int a, b, c;
		cin >> a >> b >> c;
		to[a].push_back({ b, c });
	}
	cin >> s >> e;

	dijkstra();
	checkPath();
	cout << cost[e] << "\n";
	cout << p.size() << "\n";
	for (int i = p.size()-1; i >= 0; i--)
		cout << p[i] << " ";
}

void dijkstra() {
	for (int i = 0; i <= n; i++)
		cost[i] = INF;

	cost[s] = 0;
	path[s] = -1;
	q.push({ 0, s });
	while (!q.empty()) {
		ll c = -q.top().first;
		int cur = q.top().second;
		q.pop();

		if (c > cost[cur])
			continue;

		for (int i = 0; i < to[cur].size(); i++) {
			ll nc = c + to[cur][i].second;
			int ncur = to[cur][i].first;

			if (nc < cost[ncur]) {
				cost[ncur] = nc;
				path[ncur] = cur;
				q.push({ -nc, ncur });
			}
		}
	}
	return;
}

void checkPath() {
	int cur = e;
	while (path[cur] != -1) {
		p.push_back(cur);
		cur = path[cur];
	}
	p.push_back(cur);
}
This post is licensed under CC BY 4.0 by the author.

1208 부분수열의 하1 2

17387 선분교차 2

Comments powered by Disqus.