-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstra.cpp
121 lines (95 loc) · 1.98 KB
/
Dijkstra.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <iostream>
#include<vector>
#include <list>
#include <map>
#include <algorithm>
#include <queue>
#include <string>
#include <fstream>
#include <unordered_set>
#include <stack>
#include <unordered_set>
#include <set>
using namespace std;
struct Node {
int N;
map<int, int> adjacents;
Node() {}
Node(int n) {
N = n;
}
void addAdjacent(int v, int weight) {
auto it = adjacents.find(v);
if (it == adjacents.end()) {
adjacents.insert({ v, weight });
}
else {
if (it->second > weight) {
it->second = weight;
}
}
}
};
unordered_set<int> getNodes(const int n) {
unordered_set<int> ret;
for (int i = 0; i <= n; i++)
ret.insert(i);
return ret;
}
int getMin(const vector<int>& D, const unordered_set<int>& unvisited) {
int min = D[*unvisited.begin()];
int ret = *unvisited.begin();
for (auto it : unvisited) {
if (D[it] < min) {
min = D[it];
ret = it;
}
}
return ret;
}
//n: number of edges (from 1 to n)
//graph: graph adjacent list representation
//s: the vertex to calculate the distance from
vector<int> dijkstra(int n, map<int, Node>& graph, int s) {
int INF = (int)1e9;
vector<int> D(n + 1, INF); //Dist From A
D[s] = 0;
unordered_set<int> unvisited = getNodes(n);
while (unvisited.size() > 0) {
int u = getMin(D, unvisited);
for (auto next : graph[u].adjacents) {
int v = next.first;
int weight = next.second;
if (unvisited.find(v) != unvisited.end()) {
if (D[u] + weight < D[v]) {
D[v] = D[u] + weight;
}
}
}
unvisited.erase(u);
}
return D;
}
int main()
{
int n;
cin >> n;
map<int, Node> graph;
for (int i = 1; i <= n; i++)
graph.insert({ i, Node(i) });
int v, u, w, count;
for (int i = 1; i <= n; i++) {
cin >> u;
cin >> count;
for (int j = 0; j < count; j++) {
cin >> v;
cin >> w;
graph[u].addAdjacent(v, w);
graph[v].addAdjacent(u, w);
}
}
auto result = dijkstra(n, graph, 1);
for (int i = 1; i < result.size(); i++)
cout << i << " : " << result[i] << "\n";
return 0;
}