Single Source Shortest Path algorithm
Time complexity O (N2) optimized time complexity is O (Mlogn) (M is the number of edges in the graph so it is optimized for sparse graphs faster)
does not support a graph with negative weights
Post-optimization code
Optimization of Dijkstra algorithm #include<iostream> #include <vector> #include <queue>using namespace Std;const int maxn= 1024;const int inf=1<<30; struct edge{int f,t,d;}; struct Node{int d,u;bool operator< (const node& b) Const{return d<b.d;}; int N,m;int D[MAXN],V[MAXN]; vector<int> g[maxn];vector<edge> edges;priority_queue<node> Q;void init () {for (int i=1;i<=n;i++ ) g[i].clear (); for (int i=1;i<=n;i++) v[i]=0;for (int i=2;i<=n;i++) d[i]=inf;d[1]=0; } int main () {int from,to,dist; cin>>n>>m;init (); for (int i=0;i<m;i++) {cin>>from>>to> >dist;edges.push_back (Edge) {from,to,dist}); G[from].push_back (Edges.size ()-1); Edges.push_back (Edge) {to,from,dist}); G[to].push_back (Edges.size ()-1);} Q.push (Node) {0,1}); while (! Q.empty ()) {Node x=q.top (); Q.pop (); int u=x.u;if (V[u]) continue;v[u]=1;for (int i=0;i<g[u].size (); i++) {edge& e=edges[g[u][i]];if (d[e.t] >D[U]+E.D) {D[E.T]=D[U]+E.D; Q.push (Node) {d[e.t],e.t}); }}}return 0;}
Dijkstra and optimization of the shortest path algorithm for graphs