-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathdijkstra.node3.cpp
119 lines (75 loc) · 2.06 KB
/
dijkstra.node3.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
#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;
struct Node {
int y,
cost;
};
vector<Node> Graph[ MAXN ];
int distMin[ MAXN ];
queue<Node> Queue;
bitset<MAXN> inQueue(0);
int nodes,
edges;
//prototpes functions
void readData();
void Dijkstra();
void writeData();
//main function
int main() {
readData();
Dijkstra();
writeData();
return(0);
};
void readData() {
int x;
Node node;
freopen(FIN, "r", stdin);
scanf("%d %d", &nodes, &edges);
for(int ed = 1; ed <= edges; ed++) {
scanf("%d %d %d", &x, &node.y, &node.cost);
Graph[ x ].push_back( node );
}
fclose( stdin );
};
void Dijkstra() {
Node node,
aux,
auxNode;
int k;
for(int i = 2; i <= nodes; i++) distMin[ i ] = oo;
distMin[ 1 ] = 0;
node.y = 1;
node.cost = 0;
Queue.push( node );
inQueue[ 1 ] = true;
while(!Queue.empty()) {
aux = Queue.front();
k = aux.y;
Queue.pop();
inQueue[ aux.y ] = false;
for(vector<Node>::iterator it = Graph[ aux.y ].begin();it != Graph[ aux.y ].end(); it++ ) {
if(distMin[ it->y ] > distMin[ k ] + it->cost) {
distMin[ it->y ] = distMin[ k ] + it->cost;
if(!inQueue[ it->y ]) {
auxNode.y = it->y;
auxNode.cost = distMin[ it->y ];
Queue.push( auxNode );
inQueue[ it->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 );
};