MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / bellmenFord

Function bellmenFord

CPP/graphseries.cpp:521–559  ·  view source on GitHub ↗

shortest path in a graph with -ve weights

Source from the content-addressed store, hash-verified

519
520//shortest path in a graph with -ve weights
521void bellmenFord(int source){
522 int n,m;
523 cin>>n>>m;
524 vector<node>edges;
525 for(int i=0;i<m;i++){
526 int x,y,w;
527 cin>>x>>y>>w;
528 edges.push_back(node(x,y,w));
529 }
530
531 vector<int>distance(n,INT_MAX);
532 distance[source]=0;
533
534 //relaxing N-1 times every edge
535 for(int i=0;i<=n-1;i++){
536 for(auto it:edges){
537 if(distance[it.v]>distance[it.u]+it.w){
538 distance[it.v]=distance[it.u]+it.w;
539 }
540 }
541 }
542
543 int flag=0;
544
545 //deceting negative cycle by relaxing one more time i.e Nth time
546 for(auto it:edges){
547 if(distance[it.v]>distance[it.u]+it.w){
548 cout<<"Negative cycle";
549 flag=1;
550 break;
551 }
552 }
553
554 if(flag==0){
555 for(int i=0;i<n;i++){
556 cout<<distance[i]<<" ";
557 }
558 }
559}
560
561
562int main()

Callers

nothing calls this directly

Calls 2

push_backMethod · 0.80
nodeClass · 0.70

Tested by

no test coverage detected