码迷,mamicode.com
首页 > 编程语言 > 详细

Dijkstra算法模板

时间:2015-10-15 22:17:13      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 #include<iostream>
 2 #include<cstring>
 3 #include<vector>
 4 using namespace std;
 5 struct edge{
 6     int to, cost;
 7     edge(int t, int c): to(t),cost(c) {
 8         //empty body
 9     }
10 };
11 void addEdge(vector<vector<int> > &G,vector<edge> &edgelist,int from,int to,int cost){
12     edge e = edge(to,cost);
13     edgelist.push_back(e);
14     G[from].push_back(edgelist.size()-1); // G[from] record all the edges‘ id in edgelist that connectd to it.
15 }
16 void dijkstra(vector<vector<int> > G,vector<edge> edgelist,vector<int> &dis,int v){
17     for(int i=0;i<G.size();++i) dis[i]=0x7fffffff;
18     for(int i=0;i<G[v].size();i++){
19         edge e=edgelist[ G[v][i] ];
20         dis[e.to]=e.cost;
21     }dis[v]=0;
22     
23     vector<bool> vis(G.size()); 
24     for(int i=0;i<vis.size();++i) vis[i]=false;
25     vis[v]=true;
26     
27     for(int i=1;i<G.size();++i){
28         int minDis=0x7fffffff,minPos;
29         for(int j=0;j<G.size();j++){
30             if(!vis[j]&&dis[j]<minDis){
31                 minDis=dis[j]; minPos=j;
32             }
33         }
34         vis[minPos]=true;
35         for(int p=0;p<G[minPos].size();++p){
36             edge e=edgelist[ G[minPos][p] ];
37             if(dis[minPos]+e.cost<dis[e.to]){
38                 dis[e.to]=dis[minPos]+e.cost;
39             }
40         }
41     }
42 }
43 int main(){
44     int maxn=7;
45     vector<edge> edgelist; edgelist.clear();
46     vector<vector<int> > G(maxn);
47     for(int i=0;i<G.size();++i) G[i].clear();
48     
49     addEdge(G,edgelist,0,1,4);
50     addEdge(G,edgelist,0,2,6);
51     addEdge(G,edgelist,0,3,6);
52     
53     addEdge(G,edgelist,1,2,1);
54     addEdge(G,edgelist,1,4,7);
55     
56     addEdge(G,edgelist,2,4,6); 
57     addEdge(G,edgelist,2,5,4);
58     
59     addEdge(G,edgelist,3,2,2);
60     addEdge(G,edgelist,3,5,5);
61     
62     addEdge(G,edgelist,4,6,6);
63     
64     addEdge(G,edgelist,5,4,1);
65     addEdge(G,edgelist,5,6,8);
66     
67     vector<int> dis(G.size());
68     dijkstra(G,edgelist,dis,0);
69     
70     cout<<dis[6]<<endl;
71     
72     return 0;
73     
74 }
View Code

 

Dijkstra算法模板

标签:

原文地址:http://www.cnblogs.com/fu11211129/p/4883715.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!