-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFast Dijkstra.cpp
More file actions
135 lines (116 loc) · 2.86 KB
/
Fast Dijkstra.cpp
File metadata and controls
135 lines (116 loc) · 2.86 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
130
131
132
133
134
135
#include<fstream>
#include<cstdlib>
#include<vector>
#include<queue>
#include<list>
#include<cassert>
#define inf 100000 * 1000 + 100
#define max 100001
struct TEdge{
int v, w;
};
using namespace std;
unsigned long d[max];
bool visited[max];
vector<TEdge> W[max];
template<class T>
class Heap{
private:
void Swap(T &a, T &b){
T x = a;
a = b;
b = x;
};
static int Compare(T x, T y){
if(x < y)
return -1;
else
if(y > x)
return 1;
else
return 0;
}
typedef int (*ptr_func)(T, T);
public:
vector<T> Container;
ptr_func cmp;
Heap(ptr_func _cmp = &(Compare)){cmp = _cmp;};
~Heap(){};
void push(T _val){
Container.push_back(_val);
int i = Container.size() - 1;
while((*cmp)(Container[i], Container[(i - 1) / 2]) == -1){
Swap(Container[i], Container[(i -1) / 2]);
i = (i - 1) / 2;
}
}
void pop(size_t _key){
Container[_key] = Container[Container.size() - 1];
Container.pop_back();
int i = _key, l = 2 * i + 1, r = 2 * i + 2;
size_t size = Container.size();
while(r < size && ((*cmp)(Container[i], Container[l]) == 1 ||
(*cmp)(Container[i], Container[r]) == 1))
if((*cmp)(Container[l], Container[r]) == -1){
Swap(Container[i], Container[l]);
i = l;
l = 2 * i + 1;
r = 2 * i + 2;
}
else{
Swap(Container[i], Container[r]);
i = r;
l = 2 * i + 1;
r = 2 * i + 2;
}
}
T front(){
return Container[0];
}
bool empty(){
return Container.size() == 0;
}
};
int Compare(int a, int b){
if(d[a] < d[b])
return -1;
if(d[a] > d[b])
return 1;
return 0;
}
int main(){
FILE *in = fopen("input.txt", "r"), *out = fopen("output.txt", "w");
int n, m, s;
Heap<int> q(&Compare);
fscanf(in, "%d %d %d", &n, &m, &s);
for(int i = 0; i < n + 1; i++){
d[i] = inf;
visited[i] = false;
}
for(int i = 0; i < m; i++){
int v1, v2, w;
TEdge x;
fscanf(in, "%d %d %d", &v1, &v2, &w);
x.w = w;
x.v = v2;
W[v1].push_back(x);
}
fclose(in);
int cur = s;
d[s] = 0;
q.push(s);
while(!q.empty()){
visited[cur] = true;
cur = q.front();
q.pop(0);
for(int i = 0; i < W[cur].size(); i++)
if(!visited[W[cur][i].v] && d[W[cur][i].v] > W[cur][i].w + d[cur]){
d[W[cur][i].v] = W[cur][i].w + d[cur];
q.push(W[cur][i].v);
}
}
for(int i = 1; i < n + 1; i++)
fprintf(out, "%d ", d[i] >= inf? -1: d[i]);
fclose(out);
fclose(in);
}