1#include <iostream>2#include <cstring>3#include <vector>4 using namespacestd;5 structedge{6 intto, cost;7EdgeintTintc): to (t), cost (c) {8 //Empty Body9 }Ten }; One voidAddedge (vector<vector<int> > &G,vector<edge> &edgelist,int from,intTo,intCost ) { AEdge E =Edge (to,cost); - Edgelist.push_back (e); -g[ from].push_back (Edgelist.size ()-1);//G[from] Record all the edges ' ID in edgelist that connectd to it. the } - voidDijkstra (vector<vector<int> > G,vector<edge> edgelist,vector<int> &dis,intv) { - for(intI=0; I<g.size (); ++i) dis[i]=0x7fffffff; - for(intI=0; I<g[v].size (); i++){ +Edge e=edgelist[G[v][i]]; -dis[e.to]=E.cost; +}dis[v]=0; A atvector<BOOL>Vis (G.size ()); - for(intI=0; I<vis.size (); ++i) vis[i]=false; -vis[v]=true; - - for(intI=1; I<g.size (); + +i) { - intmindis=0x7fffffff, Minpos; in for(intj=0; J<g.size (); j + +){ - if(!vis[j]&&dis[j]<Mindis) { toMINDIS=DIS[J]; minpos=J; + } - } thevis[minpos]=true; * for(intp=0;p <g[minpos].size (); + +p) { $Edge e=edgelist[G[minpos][p]];Panax Notoginseng if(dis[minpos]+e.cost<Dis[e.to]) { -dis[e.to]=dis[minpos]+E.cost; the } + } A } the } + intMain () { - intmaxn=7; $Vector<edge>edgelist; edgelist.clear (); $vector<vector<int> >G (MAXN); - for(intI=0; I<g.size (); + +i) g[i].clear (); - theAddedge (G,edgelist,0,1,4); -Addedge (G,edgelist,0,2,6);WuyiAddedge (G,edgelist,0,3,6); the -Addedge (G,edgelist,1,2,1); WuAddedge (G,edgelist,1,4,7); - AboutAddedge (G,edgelist,2,4,6); $Addedge (G,edgelist,2,5,4); - -Addedge (G,edgelist,3,2,2); -Addedge (G,edgelist,3,5,5); A +Addedge (G,edgelist,4,6,6); the -Addedge (G,edgelist,5,4,1); $Addedge (G,edgelist,5,6,8); the thevector<int>Dis (g.size ()); theDijkstra (G,edgelist,dis,0); the -cout<<dis[6]<<Endl; in the return 0; the About}
View Code
Dijkstra algorithm Templates