-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbellmanford.vector2.cpp
138 lines (87 loc) · 2.21 KB
/
bellmanford.vector2.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
126
127
128
129
130
131
132
133
134
135
136
137
#include <cstdio>
#include <vector>
#include <queue>
#include <bitset>
#define MAXN 50005
#define oo ((1LL<<31)-1)
#define FIN "bellmanford.in"
#define FOUT "bellmanford.out"
using namespace std;
vector<int> V[ MAXN ];
int distMin[ MAXN ];
queue<int> Queue;
bitset<MAXN> inQueue(0);
int countQueue[ MAXN ];
int nodes,
edges,
ok = 1;
//prototpes functions
void readData();
void BellmanFord();
void writeData();
void display1();
void display2();
//main function
int main() {
readData();
BellmanFord();
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 BellmanFord() {
for(int i = 2; i <= nodes; i++) distMin[ i ] = oo;
distMin[ 1 ] = 0;
Queue.push( 1 );
inQueue[ 1 ] = true;
while(!Queue.empty() && ok) {
int curr = Queue.front();
Queue.pop();
inQueue[ curr ] = false;
for(int i = 0; i < V[ curr ].size(); i +=2) {
int y = V[ curr ][ i + 0 ];
int cost = V[ curr ][ i + 1 ];
if(distMin[ y ] > distMin[ curr ] + cost) {
distMin[ y ] = distMin[ curr ] + cost;
if(!inQueue[ y ]) {
if(countQueue[ y ] > nodes) {
ok = 0;
} else {
countQueue[ y ]++;
Queue.push( y );
inQueue[ y ] = true;
}
}
}
}
}
};
void writeData() {
if( ok ) {
display1();
} else {
display2();
}
}
void display1() {
freopen(FOUT, "w", stdout);
for(int i = 2; i <= nodes; i++) printf("%d ", distMin[ i ]);
fclose( stdout );
};
void display2() {
freopen(FOUT, "w", stdout);
printf("%s", "Ciclu negativ!");
fclose( stdout );
};