-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDjkstra.cpp
More file actions
129 lines (116 loc) · 2.38 KB
/
Djkstra.cpp
File metadata and controls
129 lines (116 loc) · 2.38 KB
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
122
123
124
125
126
127
128
129
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
template<typename T>
class WeightedGraphs
{
unordered_map<T, list<pair<T, int>>> adj;
public:
void addEdge(T parent, T child, bool biDir, int weight)
{
adj[parent].push_back(make_pair(child, weight));
if (biDir)
{
adj[child].push_back(make_pair(parent, weight));
}
}
void printAdjList()
{
for (auto ver : adj)
{ cout << "parent is " << ver.first << "->";
for (auto nbr : ver.second)
{
cout << nbr.first << "--" << nbr.second << ",";
}
cout << "\n";
}
}
void djkstra_SET(T src, int n)
{
unordered_map<T, int> distance;
for (ll i = 0; i < n; i++)
{
distance[i] = INT_MAX;
}
distance[src] = 0;
set<pair<int, T>> s;
s.insert(make_pair(0, src));
while (!s.empty())
{
auto p = *(s.begin());
T node = p.second;
int dist = p.first;
s.erase(s.begin());
for (auto child : adj[node])
{
if (dist + child.second < distance[child.first])
{
auto f = s.find({distance[child.first], child.first});
if (f != s.end())
{
s.erase(f);
}
s.insert({dist + child.second, child.first});
distance[child.first] = dist + child.second;
}
}
}
for (auto x : distance)
{
cout << "distance of " << x.first << " is " << x.second << "\n";
}
}
void djkstra_PQ(T src, int n)
{
unordered_map<T, ll> distance;
unordered_map<T, bool> visited;
for (ll i = 1; i < n; i++)
{
distance[i] = INT_MAX;
visited[i] = false;
}
distance[src] = 0;
priority_queue< pair<int, T>, vector < pair<int, T>> , greater< pair<int, T>> > pq;
pq.push(make_pair(0, src));
while (!pq.empty())
{
auto p = pq.top();
while (visited[p.second])
{ pq.pop();
p = pq.top();
}
visited[p.second] = 1;
T node = p.second;
ll dist = p.first;
pq.pop();
for (auto child : adj[node])
{
if ((dist + child.second) < distance[child.first])
{
pq.push({dist + child.second, child.first});
distance[child.first] = dist + child.second;
}
}
}
for (auto x : distance)
{
cout << "distance of " << x.first << " is " << x.second << "\n";
}
}
};
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("otpt.txt", "w", stdout);
#endif
WeightedGraphs<int> g;
for (int i = 0; i < 12; i++)
{
int x, y, w;
cin >> x >> y >> w;
g.addEdge(x, y, 0, w);
}
g.djkstra_PQ(6, 8);
return 0;
}