Repository navigation
Expand file tree
/
Copy pathbellmanford.cpp
More file actions
86 lines (66 loc) · 1.63 KB
/
Copy pathbellmanford.cpp
File metadata and controls
86 lines (66 loc) · 1.63 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//bellman ford by neeraj patidar (O(VE)
#include <iostream>
#include <cstdlib>
#include <climits>
using namespace std;
// graph Edge --> struct
// Graph
struct Edge
{
int src,dst,wt;
};
struct graph
{
int v, e;
struct Edge * edge;
};
struct graph* create(int V,int E)
{
struct graph* g =(struct graph*)malloc(sizeof(struct graph));
g->v = V;
g->e = E;
g->edge = (struct Edge*)malloc(E*sizeof(struct Edge));
return g;
}
void bellmanford(struct graph * Graph , int src)
{
int V = Graph->v, E = Graph->e;
int d[V],pi[V];
for (int i = 0; i < E; ++i)
d[i] = INT_MAX;
d[0] = 0;
for (int i = 1; i < V-1 ; ++i)
{
for (int j = 0; j < E; ++j)
{
int a = Graph->edge[j].src;
int b = Graph->edge[j].dst;
int weight = Graph->edge[j].wt;
if(d[a] != INT_MAX && weight + d[a] < d[b])
d[b] =weight + d[a];
}
}
for (int j = 0; j < E; ++j)
{
int a = Graph->edge[j].src;
int b = Graph->edge[j].dst;
int weight = Graph->edge[j].wt;
if(d[a] != INT_MAX && weight + d[a] < d[b])
cout<<"Graph contains negetive weight cycle \n";
}
for (int i = 0; i < V; ++i)
cout<<i<<" "<<d[i]<<endl;
}
int main()
{
int v1,e1;
cin>>v1>>e1;
struct graph* Graph = create(v1,e1);
for(int i= 0;i<e1;i++)
{
cout<<"enter the source , destination, weight of "<<i+1<<" edge :";
cin>> Graph->edge[i].src >>Graph->edge[i].dst >>Graph->edge[i].wt;
}
bellmanford(Graph ,0);
return 0;
}