백준
1. 다익스트라 알고리즘
import sys
input = sys.stdlin.readline
INF = int(1e9)
n, m = map(int, input().split())
start = int(input())
graph = [[] for i in range(n + 1)]
visited = [False] * (n + 1)
distance = [INF] * (n + 1)
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append((b,c))
def get_smallest_node():
min_value = INF
index = 0
for i in range(1, n + 1):
if distance[i] < min_value and not visited[i]:
min_value = distance[i]
index = i
return index
def dijkstra(start):
distance[start] = 0
visited[start] = True
for j in graph[start]:
distance[j[0]] = j[1]
for i in range(n - 1):
now = get_smallest_node()
visited[now] = True
for j in graph[now]:
cost = distance[now] + j[1]
if cost < distance[j[0]]:
distance[j[0]] = cost
dijkstra(start)
for i in range(1, n + 1):
if distance[i] == INF:
print("INFINITY")
else:
print(distance[i])
2. C++
#include <bits/stdc++.h>
#define INF 1e9
using namespace std;
int n, m, start;
vector<pair<int, int> > graph[100001];
int d[100001];
void dijkstra(int start) {
priority_queue<pair<int, int> > pq;
pq.push({0, start});
d[start] = 0;
while (!pq.empty()) {
int dist = -pq.top().first;
int now = pq.top().second;
pq.pop();
if (d[now] < dist) continue;
for (int i = 0; i < graph[now].size(); i++) {
int cost = dist + graph[now][i].second;
if (cost < d[graph[now][i].first]) {
d[graph[now][i].first] = cost;
pq.push(make_pair(-cost, graph[now][i].first));
}
}
}
}
int main(void) {
cin >> n >> m >> start;
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
graph[a].push_back({b, c});
}
fill(d, d + 100001, INF);
dijkstra(start);
for (int i = 1; i <= n; i++) {
if (d[i] == INF) {
cout << "INF" << '\n';
}
else {
cout << d[i] << '\n';
}
}
}