Posts 1753 최단경로
Post
Cancel

1753 최단경로

1753 최단경로

알고리즘

1
1. 다익스트라

코드

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
#include <iostream>
#include <queue>
#include <vector>
#define INF 2000000000;
using namespace std;

int V, E, s, length[20001];
vector<pair<int, int>> node[20001];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
bool check[20001];

void dijkstra();

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin >> V >> E >> s;

	for (int i = 0; i < E; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		node[a].push_back({ b, c });
	}

	for (int i = 1; i <= V; i++)
		length[i] = INF;

	length[s] = 0;

	dijkstra();

	for (int i = 1; i <= V; i++) {
		if (length[i] != 2000000000)
			cout << length[i] << '\n';
		else
			cout << "INF\n";
	}
}

void dijkstra() {
	q.push({ 0, s });

	while (!q.empty()) {
		int d = q.top().first, cur = q.top().second;
		q.pop();

		if (d > length[cur] || check[cur])
			continue;

		for (int i = 0; i < node[cur].size(); i++) {
			int next = node[cur][i].first, nd = d + node[cur][i].second;
			if (nd < length[next]) {
				q.push({ nd, next });
				length[next] = nd;
			}
		}
		check[cur] = true;
	}
}
This post is licensed under CC BY 4.0 by the author.

17404 RGB Distance 2

17837 새로운게임2 Samsung sw test

Comments powered by Disqus.