-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbellmanford3.cpp
106 lines (65 loc) · 1.5 KB
/
bellmanford3.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
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
#define oo 1<<30
#define MAX 50001
#define pb push_back
using namespace std;
struct nod {
int y,
c;
};
vector <nod> V[ MAX ];
deque <int> QUEUE;
int n,
m,
dist[ MAX ],
count[ MAX ];
void read() {
ifstream fin("bellmanford.in");
fin>>n>>m;
int x,
c;
nod t;
for(int i = 1; i <= m; i++) {
fin>>x>>t.y>>t.c;
V[ x ].pb( t );
}
fin.close();
};
int BellmanFord() {
for(int i = 2; i <= n; i++)
dist[ i ] = oo;
dist[ 1 ] = 0;
QUEUE.pb( 1 );
while( !QUEUE.empty() ) {
int x = QUEUE.front();
if( dist[ x ] != oo ) {
for(int i = 0; i < V[ x ].size(); i++) {
int y = V[ x ][ i ].y,
c = V[ x ][ i ].c;
if( dist[ y ] > dist[ x ] + c ) {
dist[ y ] = dist[ x ] + c;
QUEUE.pb( y );
if(++count[ y ] > n - 1) return 0;
}
}
}
QUEUE.pop_front();
}
return 1;
};
int main() {
ofstream fout("bellmanford.out");
read();
if( BellmanFord() ) {
for(int i = 2; i <= n; i++) {
fout<<dist[ i ]<<" ";
}
} else {
fout<<"Ciclu negativ!";
}
fout.close();
return (0);
}