C++ Code For Classic Algorithms: Dijkstra's Algo
C++ Code For Classic Algorithms: Dijkstra's Algo
Dijkstra’s Algo :
// TC-> O((N+E)logN)
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int>
> > pq;// min-heap ; In pair => (dist,node)
distTo[source] = 0;
pq.push(make_pair(0,source)); // (dist,node)
while( !pq.empty() )
pq.pop();
pq.push(make_pair(distTo[next], next));
return distTo;
fi
fi
Bellman Ford :
//this also gives shortest path from a chosen source to every other node
but won't work when negative edge weights are there
//so advantage compared to dijkstra is that in -ve weight case ,it will
atleast detect a negative cycle
//b/w 2 nodes split into two each having weight as the previous weight.
//TC->O( N-1 * E )
struct node {
int u;
int v;
int wt;
u = rst;
v = second;
wt = weight;
};
dist[src] = 0;
int = 0;
fl
fi
fi
cout << "Negative Cycle";
= 1;
break;
if(! ) //Negative cycle wasn't found and the shortest distance from
src to every node can be returned
for(int i = 0;i<N;i++)
vis[node] = 1;
if(!vis[it])
st.push(node);
vis[node] = 1;
if(!vis[it])
fl
fl
fi
fi
fi
fi
void KosarajuSCC(int n,vector<vector<int>>&graph)
stack<int> st;
for(int i = 0;i<n;i++)
if(!vis[i])
vector<vector<int>> transpose(n);
for(int i = 0;i<n;i++)
vis[i] = 0;
transpose[it].push_back(i);
while(!st.empty())
st.pop();
if(!vis[node])
cout <<"\n";