-
Notifications
You must be signed in to change notification settings - Fork 4k
/
BellmanFord.cpp
129 lines (103 loc) · 2.05 KB
/
BellmanFord.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <iostream>
using namespace std;
struct edge
{
int u, v, w;
};
struct Graph
{
int V, E;
struct edge *e;
};
struct Graph *create(int V, int E)
{
struct Graph *g = new Graph;
g->V = V;
g->E = E;
g->e = new edge[E];
return g;
};
void ford(struct Graph *g, int S)
{
int V = g->V;
int E = g->E;
int D[V];
for (int i = 0; i < V; i++)
{
D[i] = INT_MAX;
}
D[S] = 0;
for (int i = 1; i <= V - 1; i++)
{
for (int j = 0; j < E; j++)
{
int u = g->e[j].u;
int v = g->e[j].v;
int w = g->e[j].w;
if (D[u] != INT_MAX && D[u] + w < D[v])
{
D[v] = D[u] + w;
}
}
}
for (int j = 0; j < E; j++)
{
int u = g->e[j].u;
int v = g->e[j].v;
int w = g->e[j].w;
if (D[u] != INT_MAX && D[u] + w < D[v])
{
cout << "Err.. Negative Cycle";
return;
}
}
cout << "Source Destination Distance From Source\n";
for (int i = 0; i < V; i++)
printf("%d\t\t%d\n", i, D[i]);
return;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("inp1.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(0);
cin.tie(0);
int V = 5;
int E = 8;
int a, b, c, d;
struct Graph *gph = create(V, E);
/* for(int i=0;i<E;i++)
{
cin>>a>>b>>c;
g->e[i].u = a;
g->e[i].v = b;
g->e[i].w = c;
}*/
gph->e[0].u = 0;
gph->e[0].v = 1;
gph->e[0].w = -1;
gph->e[1].u = 0;
gph->e[1].v = 2;
gph->e[1].w = 4;
gph->e[2].u = 1;
gph->e[2].v = 2;
gph->e[2].w = 3;
gph->e[3].u = 1;
gph->e[3].v = 3;
gph->e[3].w = 2;
gph->e[4].u = 1;
gph->e[4].v = 4;
gph->e[4].w = 2;
gph->e[5].u = 3;
gph->e[5].v = 2;
gph->e[5].w = 5;
gph->e[6].u = 3;
gph->e[6].v = 1;
gph->e[6].w = 1;
gph->e[7].u = 4;
gph->e[7].v = 3;
gph->e[7].w = -3;
ford(gph, 0);
}