-
Notifications
You must be signed in to change notification settings - Fork 59
/
bellman ford.cpp
52 lines (51 loc) · 1.02 KB
/
bellman ford.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
# include <fstream>
# include <vector>
# include <queue>
# include <algorithm>
# define inf 1000000000
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
struct elem
{
int y,val;
}X,Y;
vector <elem> v[50005];
queue <int> q;
int i,j,n,m,x,y,k;
int dist[50005],ap[50005];
int main ()
{
f>>n>>m;
for (i=2; i<=n; ++i)
dist[i]=inf;
for (i=1; i<=m; ++i)
{
f>>x>>X.y>>X.val;
v[x].push_back(X);
}
q.push(1);
while (!q.empty())
{
k=q.front (); q.pop();
++ap[k];
if (ap[k]>n) {
g<<"Ciclu negativ!\n";
return 0;
}
for (i=0; i<v[k].size(); ++i)
{
if (dist[v[k][i].y]>dist[k]+v[k][i].val)
{
dist[v[k][i].y]=dist[k]+v[k][i].val;
q.push(v[k][i].y);
}
}
}
for (i=2; i<=n; ++i)
{
if (dist[i]==inf) g<<"0 ";
else g<<dist[i]<<" ";
}
return 0;
}