-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdijkstra.vector.cpp
105 lines (67 loc) · 1.77 KB
/
dijkstra.vector.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
#include <cstdio>
#include <vector>
#include <queue>
#include <bitset>
#define MAXN 50005
#define oo ((1LL<<31)-1)
#define FIN "dijkstra.in"
#define FOUT "dijkstra.out"
using namespace std;
vector<int> V[ MAXN ];
int distMin[ MAXN ];
queue<int> Queue;
bitset<MAXN> inQueue(0);
int nodes,
edges;
//prototpes functions
void readData();
void Dijkstra();
void writeData();
void printV();
//main function
int main() {
readData();
Dijkstra();
writeData();
return(0);
};
void readData() {
int x,
y,
cost;
freopen(FIN, "r", stdin);
scanf("%d %d", &nodes, &edges);
for(int ed = 1; ed <= edges; ed++) {
scanf("%d %d %d", &x, &y, &cost);
V[ x ].push_back( y );
V[ x ].push_back( cost );
}
fclose( stdin );
};
void Dijkstra() {
for(int i = 2; i <= nodes; i++) distMin[ i ] = oo;
distMin[ 1 ] = 0;
Queue.push( 1 );
inQueue[ 1 ] = true;
while(!Queue.empty()) {
int node_curr = Queue.front();
Queue.pop();
inQueue[ node_curr ] = false;
for(int i = 0; i < V[ node_curr ].size(); i += 2) {
int y = V[ node_curr ][ i + 0 ];
int cost = V[ node_curr ][ i + 1 ];
if(distMin[ y ] > distMin[ node_curr ] + cost) {
distMin[ y ] = distMin[ node_curr ] + cost;
if(!inQueue[ y ]) {
Queue.push( y );
inQueue[ y ] = true;
}
}
}
}
};
void writeData() {
freopen(FOUT, "w", stdout);
for(int i = 2; i <= nodes; i++) printf("%d ", (distMin[ i ] < oo) ? distMin[ i ] : 0);
fclose( stdout );
};