-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra[sparsegraph].cpp
executable file
·51 lines (40 loc) · 1.22 KB
/
dijkstra[sparsegraph].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
/** Dijkstra on sparse graphs
- complexity : O(n + m)logn -> O(nlogn + m)
- Single Source Single Destination Shortest Path Problem
- Positive Weight Edges only
* Subpaths of shortest paths from u to v are shortest paths!
**/
const int N = 1e5 + 9, M = 2e5 + 9, oo = 0x3f3f3f3f;
ll INF = 0x3f3f3f3f3f3f3f3f;
int Head[N], Par[N], Next[M], To[M], Cost[M], ne, n, m, u, v, st, tr, tax;
ll dis[N];
void addEdge(int from, int to, int cost) {
Next[++ne] = Head[from];
Head[from] = ne;
Cost[ne] = cost;
To[ne] = to;
}
void _clear() {
memset(Head, 0, sizeof(Head[0]) * (n + 2));
ne = 0;
}
void Dijkstra(int src, int trg) {
memset(dis, 0x3f, sizeof(dis[0]) * (n + 2));
memset(Par, -1, sizeof(Par[0]) * (n + 2));
priority_queue <pair <ll, int> > Q;
dis[src] = 0;
Q.push({-dis[src], src});
int node;
ll cost;
while(Q.size()) {
tie(cost, node) = Q.top(); Q.pop();
if((-cost) > dis[node]) continue; // lazy deletion
if(node == trg) return; // cheapest cost in case of positive weight edges
for(int i = Head[node]; i; i = Next[i])
if(dis[node] + Cost[i] < dis[To[i]]) {
dis[To[i]] = dis[node] + Cost[i];
Q.push({-dis[To[i]], To[i]});
Par[To[i]] = node;
}
}
}