Advertisement
GamerBhai02

10. Bellman Ford

Nov 25th, 2024 (edited)
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | Source Code | 0 0
  1. https://onlinegdb.com/FqPuQyRvk
  2. #include <stdio.h>
  3. #include <limits.h>
  4. #define INF INT_MAX
  5. typedef struct {
  6.     int u, v, weight;
  7. }Edge;
  8. void bellmanFord(int n,int m,Edge edges[],int source){
  9.     int dist[n];
  10.     for(int i=0;i<n;i++){
  11.         dist[i] = INF;
  12.     }
  13.     dist[source] = 0;
  14.     for(int i=0;i<n;i++){
  15.         for(int j=0;j<m;j++){
  16.             int u = edges[j].u;
  17.             int v = edges[j].v;
  18.             int weight = edges[j].weight;
  19.             if(dist[u]!=INF && dist[u]+weight<dist[v]){
  20.                 dist[v] = dist[u]+weight;
  21.             }
  22.         }
  23.     }
  24.     for(int j=0;j<m;j++){
  25.         int u = edges[j].u;
  26.         int v = edges[j].v;
  27.         int weight = edges[j].weight;
  28.         if(dist[u]!=INF && dist[u]+weight<dist[v]){
  29.             printf("Graph contains negative weight cycle\n");
  30.             return;
  31.         }
  32.     }
  33.     for(int i=0;i<n;i++){
  34.         if(dist[i]==INF){
  35.             printf("%d\n",i);
  36.         }else{
  37.             printf("%d: %d\n",i,dist[i]);
  38.         }
  39.     }
  40. }
  41. int main(){
  42.     int n,m;
  43.     printf("Enter number of bus stops: ");
  44.     scanf("%d",&n);
  45.     printf("Enter number of edges: ");
  46.     scanf("%d",&m);
  47.     Edge edges[m];
  48.     printf("Enter source, destination and weight (travel time): ");
  49.     for(int i=0;i<m;i++){
  50.         scanf("%d %d %d",&edges[i].u,&edges[i].v,&edges[i].weight);
  51.     }
  52.     int source;
  53.     printf("Enter source bus stop: ");
  54.     scanf("%d",&source);
  55.     bellmanFord(n,m,edges,source);
  56.     return 0;
  57. }
Tags: Bellman ford
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement