Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int dist[100];
- struct Edge
- {
- int source, dest, cost;
- };
- Edge edge[100];
- void print(int n)
- {
- printf("Vertex Distance from Source\n");
- }
- void BellmanFord(int v, int e, int source)
- {
- for (int i = 0; i<=v; i++) dist[i] = 10000;
- dist[source] = 0;
- for (int i=1; i<=v-1; i++)
- {
- for (int j=0; j<e; j++)
- {
- int u = edge[j].source;
- int v = edge[j].dest;
- int cost = edge[j].cost;
- if (dist[u]!=10000 && dist[u]+cost<dist[v])
- dist[v] = dist[u] + cost;
- }
- }
- for (int i=0; i<e; i++)
- {
- int u = edge[i].source;
- int v = edge[i].dest;
- int cost = edge[i].cost;
- if (dist[u]!=10000 && dist[u]+cost<dist[v])
- printf("Negative Cycle\n\n");
- }
- printf("\n");
- for (int i=1; i<=v; i++)
- printf("Vertex %d Distance %d\n", i, dist[i]);
- return;
- }
- int main()
- {
- int v,e;
- scanf("%d%d", &v, &e);
- int i, j;
- int source, dest, cost;
- for(i=0; i<e; i++)
- {
- scanf("%d%d%d", &source, &dest, &cost);
- edge[i].source = source;
- edge[i].dest = dest;
- edge[i].cost = cost;
- }
- int s;
- cout << "Enter source: ";
- cin >> s;
- BellmanFord(v, e, s);
- return 0;
- }
Add Comment
Please, Sign In to add comment