Created
April 22, 2017 20:58
-
-
Save shubham100795/d895cb65a77463f763acc426b343b483 to your computer and use it in GitHub Desktop.
single source shortest path using stl in c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
#define INF 0x3f3f3f3f | |
#define V 4 | |
using namespace std; | |
list< pair<int,int> > adj[V]; | |
void addedge(int u,int v,int w) | |
{ | |
adj[u].push_back(make_pair(v,w)); | |
} | |
void shortestpath(int src) | |
{ | |
set< pair<int,int> > setds; | |
vector<int> dist(V,INF); | |
setds.insert(make_pair(0,src)); | |
dist[src]=0; | |
while(!setds.empty()) | |
{ | |
pair<int,int> temp= *(setds.begin()); | |
setds.erase(setds.begin()); | |
int u=temp.second; | |
list<pair<int,int> >::iterator i; | |
for(i=adj[u].begin();i!=adj[u].end();i++) | |
{ | |
int v=(*i).first;//vertex adjacent to u | |
int w=(*i).second;//weight of edge u--->v | |
if(dist[v]>dist[u]+w) | |
{ | |
//IF THE VERTEX "V" IS ALREADY IN OUR SET THEN FIRST ERASE THEN INSERT AGAIN AFTER UPADTING DISTANCE | |
if(dist[v]!=INF) | |
setds.erase(setds.find(make_pair(dist[v],v))); | |
dist[v]=dist[u]+w; | |
setds.insert(make_pair(dist[v],v)); | |
} | |
} | |
} | |
for(int i=0;i<V;i++) | |
cout<<dist[i]<<" "; | |
} | |
int main() | |
{ | |
addedge(0,1,1); | |
addedge(1,3,2); | |
addedge(3,2,3); | |
addedge(0,2,8); | |
addedge(0,3,5); | |
shortestpath(0); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment