-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBellman-Ford algorithm.cpp
More file actions
57 lines (54 loc) · 976 Bytes
/
Copy pathBellman-Ford algorithm.cpp
File metadata and controls
57 lines (54 loc) · 976 Bytes
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
#include <bits/stdc++.h>
using namespace std;
struct edges
{
int u;
int v;
int wt;
};
int main()
{
vector<edges> vec;
int n, e, source;
cout << "Enter number of nodes,edges and the source:" << "\n";
cin >> n >> e >> source;
vector<int> dist(n, 1e7);
dist[source] = 0;
cout << "Enter edges" << "\n";
for (int i = 0; i < e; i++)
{
int u, v, wt;
cin >> u >> v >> wt;
vec.push_back({ u, v, wt });
}
for (int i = 1; i <= n - 1; i++)
{
for (auto it: vec)
{
if (dist[it.u] + it.wt < dist[it.v])
{
dist[it.v] = dist[it.u] + it.wt;
}
}
}
int flag = 0;
for (auto it: vec)
{
if (dist[it.u] + it.wt < dist[it.v])
{
flag = 1;
}
}
if (flag == 1)
{
cout << "Negative cycle detected" << "\n";
}
else
{
cout << "Shortest distance from source " << source << " is: " << "\n";
for (int i = 0; i < n; i++)
{
cout << "Node " << i << " : " << dist[i] << "\n";
}
}
}