-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdijkstra-algorithm.cpp
92 lines (57 loc) · 1.63 KB
/
dijkstra-algorithm.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
#include <cstdio>
#include <vector>
#include <queue>
#define FIN "dijkstra.in"
#define FOUT "dijkstra.out"
#define MAXN 50005
#define oo ((1LL << 31) - 1)
using namespace std;
vector< pair<int, int> > Graph[ MAXN ];
queue< int > Q;
int nodes,//number of nodes
edges;//number of edges
int distMin[ MAXN ];
bool in_Queue[ MAXN ];
void readData() {
int x,
y,
c;
freopen(FIN, "r", stdin);
scanf("%d %d", &nodes, &edges);
while(edges--) {
scanf("%d %d %d", &x, &y, &c);
Graph[ x ].push_back(make_pair(y, c));
}
fclose(stdin);
};
void Dijkstra(){
for(int i = 2; i <= nodes; i++) distMin[ i ] = oo;
distMin[ 1 ] = 0;
Q.push( 1 );
in_Queue[ 1 ] = true;
while( !Q.empty() ) {
int node = Q.front();
Q.pop();
in_Queue[ node ] = false;
for(vector< pair<int,int> >::iterator it = Graph[ node ].begin(); it != Graph[ node ].end(); it++) {
if( distMin[ it->first ] > distMin[ node ] + it->second ) {
distMin[ it->first ] = distMin[ node ] + it->second;
if( !in_Queue[ it->first ] ) {
Q.push(it->first);
in_Queue[ it->first ] = true;
}
}
}
}
};
void writeData(){
freopen(FOUT, "w", stdout);
for(int i = 2; i <= nodes; i++) printf("%d ", (distMin[ i ] < oo) ? distMin[ i ] : 0);
fclose( stdout );
};
int main() {
readData();
Dijkstra();
writeData();
return(0);
};