Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://onlinegdb.com/FqPuQyRvk
- #include <stdio.h>
- #include <limits.h>
- #define INF INT_MAX
- typedef struct {
- int u, v, weight;
- }Edge;
- void bellmanFord(int n,int m,Edge edges[],int source){
- int dist[n];
- for(int i=0;i<n;i++){
- dist[i] = INF;
- }
- dist[source] = 0;
- for(int i=0;i<n;i++){
- for(int j=0;j<m;j++){
- int u = edges[j].u;
- int v = edges[j].v;
- int weight = edges[j].weight;
- if(dist[u]!=INF && dist[u]+weight<dist[v]){
- dist[v] = dist[u]+weight;
- }
- }
- }
- for(int j=0;j<m;j++){
- int u = edges[j].u;
- int v = edges[j].v;
- int weight = edges[j].weight;
- if(dist[u]!=INF && dist[u]+weight<dist[v]){
- printf("Graph contains negative weight cycle\n");
- return;
- }
- }
- for(int i=0;i<n;i++){
- if(dist[i]==INF){
- printf("%d\n",i);
- }else{
- printf("%d: %d\n",i,dist[i]);
- }
- }
- }
- int main(){
- int n,m;
- printf("Enter number of bus stops: ");
- scanf("%d",&n);
- printf("Enter number of edges: ");
- scanf("%d",&m);
- Edge edges[m];
- printf("Enter source, destination and weight (travel time): ");
- for(int i=0;i<m;i++){
- scanf("%d %d %d",&edges[i].u,&edges[i].v,&edges[i].weight);
- }
- int source;
- printf("Enter source bus stop: ");
- scanf("%d",&source);
- bellmanFord(n,m,edges,source);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement