forked from deepdarshan21/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bellman-ford.cpp
67 lines (60 loc) · 1.51 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
using namespace std;
class Edge{
public:
int source;
int dest;
int weight;
};
void bellman_ford(Edge *input,int n,int e,int s)
{
int weight[n+1];
for(int i=0;i<n;i++)
weight[i]=INT_MAX;
weight[s]=0;
for(int i=0;i<n;i++)
{
cout<<weight[i]<<" ";
}
cout<<endl;
for(int pass=0;pass<n-1;pass++)
{
cout<<"Pass:"<<pass+1<<endl;
for(int i=0;i<e;i++)
{ Edge curr=input[i];
if(weight[curr.source]!=INT_MAX and weight[curr.dest]>weight[curr.source]+curr.weight)
{
weight[curr.dest]=weight[curr.source]+curr.weight;
}
}
for(int i=0;i<n;i++)
{
cout<<weight[i]<<" ";
}
cout<<endl;
}
for(int i=0;i<e;i++)
{ Edge curr=input[i];
if(weight[curr.source]!=INT_MAX and weight[curr.dest]>weight[curr.source]+curr.weight)
{
cout<<"Graph contain Negetive cycle!";
return;
}
}
}
int main()
{
int n,e;
cin>>n>>e;
Edge* input = new Edge[e];
for(int i=0;i<e;i++)
{
int s,d,w;
cin>>s>>d>>w;
input[i].source = s;
input[i].dest = d;
input[i].weight = w;
}
bellman_ford(input,n,e,0);
return 0;
}