-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdijkstra.class.cpp
125 lines (80 loc) · 2.17 KB
/
dijkstra.class.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
122
123
124
125
#include <cstdio>
#include <vector>
#include <queue>
#define FIN "dijkstra.in"
#define FOUT "dijkstra.out"
using namespace std;
class Dijkstra {
public:
Dijkstra(int N, int M): nodes( N ),
edges( M ),
Graph(2 * N + 1),
distMin(2 * N + 1),
inQueue(N + 1) {}
void addEdge(int x, int y, int cost) {
Graph[ x ].push_back(make_pair(y, cost));
}
void solve() {
for(int i = 2; i <= nodes; i++) distMin[ i ] = oo;
distMin[ 1 ] = 0;
Queue.push( 1 );
inQueue[ 1 ] = true;
while( !Queue.empty() ) {
int node = Queue.front();
Queue.pop();
inQueue[ node ] = false;
for(auto G : Graph[ node ]) {
if(distMin[ G.first ] > distMin[ node ] + G.second) {
distMin[ G.first ] = distMin[ node ] + G.second;
if(!inQueue[ G.first ]) {
Queue.push( G.first );
inQueue[ G.first ] = true;
}
}
}
}
}
void getDistMin() {
freopen(FOUT, "w", stdout);
for(int i = 2; i <= nodes; i++) {
printf("%d ", distMin[ i ] < oo ? distMin[ i ] : 0);
}
fclose( stdout );
}
void printGraph() {
printf("\n");
for(int i = 1 ; i <= nodes; i++) {
printf("%d - > ", i);
for(auto v : Graph[ i ]) {
printf("%d ", v.first);
}
printf("\n");
}
printf("\n");
}
private:
int nodes, edges;
vector<vector<pair<int, int> > > Graph;
vector<int> distMin;
queue<int> Queue;
vector<bool> inQueue;
int oo = ((1LL<<31)-1);
};
int main() {
int n,
m,
x,
y,
cost;
freopen(FIN, "r", stdin);
scanf("%d %d", &n, &m);
Dijkstra dij(n, m);
while(m--){
scanf("%d %d %d", &x, &y, &cost);
dij.addEdge(x, y, cost);
}
dij.solve();
dij.getDistMin();
fclose( stdin );
return(0);
};