Skip to content

Commit b8c149e

Browse files
authored
Bellman_Ford_implementation.cpp
Bellman Ford algorithm implemented in C++
1 parent 19d8307 commit b8c149e

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
// BELLMAN FORD ALGORITHM TO DETECT NEGATIVE CYCLE IN GRAPHS....
2+
3+
4+
5+
6+
7+
#include <bits/stdc++.h>
8+
using namespace std;
9+
10+
typedef long long int ll;
11+
using ii= pair<ll,ll>;
12+
#define F first
13+
#define S second
14+
#define MP make_pair
15+
#define PB push_back
16+
17+
18+
struct Edge{ // we implement it using struct edge where each edge stores the edge details..
19+
ll a,b,c; //a->node,b->node,c->cost (c)
20+
//a--------->b
21+
};
22+
23+
24+
vector<Edge> v; // instead of creating a vector of piars , create a vector of edges where each element of the
25+
// vector is an edge....
26+
void Bellman_Ford(ll n,ll m) // n-> nodes_no, m-> no_of_edges..
27+
{
28+
vector<ll> d(n,1e18); //holding min distance of nodes....
29+
d[0]= 0; // initializing src at 0 distance
30+
31+
ll x; // x-> flag for negative cycle....
32+
33+
for(ll i=0;i;i++) // after i iterations, i nodes will have attained there min distance provided -ve cycles not involved...
34+
{<n
35+
x=-1;
36+
37+
for(ll j=0;j<m;j++) // loop on all edges
38+
{
39+
if(d[v[j].b]>d[v[j].a]+v[j].c) // relax distance if u get any min_path
40+
{
41+
d[v[j].b]=d[v[j].a]+v[j].c;
42+
x= v[j].a;
43+
}
44+
}
45+
}
46+
47+
48+
if(x!=-1)
49+
{
50+
cout<<"possible\n"; // got a negative cycle....
51+
}
52+
53+
else{
54+
cout<<"not possible\n"; // otherwise not....
55+
}
56+
57+
58+
}
59+
60+
int main()
61+
{
62+
ios_base::sync_with_stdio(false);
63+
cin.tie(NULL);cout.tie(NULL);
64+
65+
ll t;
66+
cin>>t;
67+
while(t--)
68+
{
69+
ll n,m;
70+
cin>>n>>m;
71+
72+
v.resize(m+1); // very important ...u may get RE if u dont resize v
73+
v.clear(); // u must clear v if there are more than 1 test cases....
74+
75+
76+
for(ll i=0;i<m;i++)
77+
{
78+
ll x,y,z;
79+
cin>>x>>y>>z;
80+
81+
v.PB({x,y,z});
82+
}
83+
84+
85+
Bellman_Ford(n,m);
86+
87+
88+
}
89+
}
90+
91+
92+
93+
94+

0 commit comments

Comments
 (0)