-
Notifications
You must be signed in to change notification settings - Fork 1
/
bellmanford.cpp
75 lines (75 loc) · 1.06 KB
/
bellmanford.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
// Distance from source ,Works in all cases , identifies negative weight cycles
#include <bits/stdc++.h>
using namespace std;
struct nodes
{
int v1, v2, wt;
};
vector<struct nodes> g;
vector<int> arr;
int v, E;
int bmfd()
{
for (int i = 0; i < v; i++)
{
int count = 0;
vector<int> vis(v + 1, 0);
for (int j = 0; j < E; j++)
{
int s1 = g[j].v1;
int s2 = g[j].v2;
int w = g[j].wt;
if (arr[s2] > arr[s1] + w)
{
arr[s2] = arr[s1] + w;
if (vis[s2] == 0)
{
count++;
vis[s2] = 1;
}
}
}
if (i == v - 1 && count != 0)
{
return 1;
}
else if (count == v)
{
return 1;
}
else if (count == 0)
{
return 0;
}
}
return 0;
}
int main()
{
cin >> v >> E;
arr.resize(v + 1);
for (int i = 0; i < E; i++)
{
struct nodes a;
cin >> a.v1 >> a.v2 >> a.wt;
g.push_back(a);
}
for (int i = 1; i <= v; i++)
{
arr[i] = 10000;
}
arr[1] = 0;
int p = bmfd();
if (p == 1)
{
cout << "NEGATIVE CYCLE EXISTS!";
}
else
{
for (int i = 1; i <= v; i++)
{
cout << i << ":" << arr[i] << " ";
}
}
cout << endl;
}