-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQuestion 2(B).cpp
More file actions
84 lines (77 loc) · 1.85 KB
/
Question 2(B).cpp
File metadata and controls
84 lines (77 loc) · 1.85 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
#include<iostream>
#include<conio.h>
#include<cstdlib>
using namespace std;
struct Edge {
int u;
int v;
int w;
};
struct Graph {
int V;
int E;
struct Edge *edge;
};
void bellmanford(Graph *g, int source) {
int u, v, w;
int d[g->V];
int p[g->V];
for (int i = 0; i < g->V; i++) {
d[i] = INT_MAX;
p[i] = 0;
}
d[source] = 0;
for(int i = 1; i <= g->V-1; i++) {
for(int j = 0; j < g->E; j++) {
u = g->edge[j].u;
v = g->edge[j].v;
w = g->edge[j].w;
if(d[u] != INT_MAX && d[v] > d[u] + w) {
d[v] = d[u] + w;
p[v] = u;
}
}
}
for(int i = 0; i < g->E; i++) {
u = g->edge[i].u;
v = g->edge[i].v;
w = g->edge[i].w;
if(d[u] != INT_MAX && d[v] > d[u] + w) {
cout << "\nGraph contains Negative Weight Cycle!\n";
return;
}
}
cout << "\nVertex\t\t:\t";
for(int i = 0; i < g->V; i ++) {
cout << i << "\t";
}
cout << "\nDistance\t:\t";
for(int i = 0; i < g->V; i ++) {
cout << d[i] << "\t";
}
cout << "\nParent\t\t:\t";
for(int i = 0; i < g->V; i ++) {
cout << p[i] << "\t";
}
cout << endl;
}
int main() {
Graph *g = (Graph*)malloc(sizeof(Graph));
cout << "\nEnter Number of Vertices\t:\t";
cin >> g->V;
cout << "\nEnter Number of Edges\t:\t";
cin >> g->E;
g->edge = (Edge*)malloc(g->E*sizeof(Edge));
cout << "\nEnter Edge (source , destination , weight)\n";
for ( int i = 0; i < g->E; i++ ) {
cout << "\nEnter values for " << i+1 << " Edge\n";
cin >> g->edge[i].u;
cin >> g->edge[i].v;
cin >> g->edge[i].w;
}
cout << "\nEnter Source Vertex\t:\t";
int s;
cin >> s;
bellmanford(g, s);
return 0;
}