-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBellman.cpp
More file actions
65 lines (61 loc) · 1.39 KB
/
Bellman.cpp
File metadata and controls
65 lines (61 loc) · 1.39 KB
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
#include <bits/stdc++.h>
using namespace std;
void bell(int edge[][3], int n, int m)
{
int dis[n];
for (int i = 0; i < n; i++)
dis[i] = 100000;
dis[0] = 0;
for (int i = 1; i < n - 1; i++)
{
for (int j = 0; j < m; j++)
{
int src = edge[j][0];
int dest = edge[j][1];
int w = edge[j][2];
if (dis[src] != 100000 && dis[src] + w < dis[dest])
{
dis[dest] = dis[src] + w;
}
}
}
for (int i = 0; i < n; i++)
cout << dis[i] << " ";
// Step 3: detect negative cycle
// if value changes then we have a negative cycle in the graph
// and we cannot find the shortest distances
for (int i = 0; i < m; i++)
{
int u = edge[i][0];
int v = edge[i][1];
int w = edge[i][2];
if (dis[u] != 100000 && dis[u] + w < dis[v])
{
printf("Graph contains negative w cycle");
return;
}
}
}
int main()
{
int n, m; // vertex,edge
cin >> n >> m;
int edge[m][3];
int s, d, w;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < 3; j++)
{
cin >> edge[i][j];
}
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < 3; j++)
{
cout << edge[i][j] << " ";
}
cout << endl;
}
bell(edge, n, m);
}