最短路 HDU - 2544(题解)

原题

原题链接

题目大意

题目可以抽象成一个图,给定一个无向连通图,问两点间的最短路径.

题目分析

该题是裸的最短路径问题,可以用来当作最短路径算法练习,这里主要讲一下dijkstra算法思路,先创建一个d[i]数组(初始化为inf),表示第i个点与起点的距离,从第s个点开始,先找出与s点连接的边,把这些边存起来,从其中找一个权值最小的边来更新顶点同时将该边移除(这里假设s更新为x),到了x之后再把与x顶点连接的边和前面存的边一起存起来,再从这堆边中,假设边按权值从小到大排序,从最小的边开始寻找符合(d[前进的顶点]=d[当前的顶点]+cost)的边并在此更新顶点(同时移除该边),如此重复直到所有顶点都被更新完毕即可.

代码

 1 #include <cstdio>
 2 #include <cmath>
 3 #include <iostream>
 4 #include <cstring>
 5 #include <algorithm>
 6 #include <vector>
 7 #include <string>
 8 #include <utility>
 9 #include <queue>
10 #include <stack>
11 #include <map> 
12 const int INF=0x3f3f3f3f;
13 using namespace std; 
14 
15 //DijkstraËã·¨
16 struct edge
17 {
18     int to,cost;
19     edge (){}
20     edge (int x,int y){to=x,cost=y;};
21 };
22 typedef pair<int,int> P; //firstÊÇ×î¶Ì¾àÀ룬secondÊǶ¥µãµÄ±àºÅ
23 
24 int V;
25 vector<edge> G[101];
26 int d[101];
27 
28 void dijkstra(int s)
29 {
30     priority_queue<P,vector<P>,greater<P> > que;
31     fill(d,d+V+1,INF);
32     d[s]=0;
33     que.push(P(0,s));
34     
35     while(!que.empty())
36     {
37         P p=que.top();que.pop();
38         int v=p.second;
39         if(d[v]<p.first) continue;
40         for(int i=0;i<G[v].size();i++)
41         {
42             edge e=G[v][i];
43             if(d[e.to]>d[v]+e.cost)
44             {
45                 d[e.to]=d[v]+e.cost;
46                 que.push(P(d[e.to],e.to));
47             }
48         }
49     } 
50 } 
51 
52 int main()
53 {
54     int e; 
55     while(cin>>V>>e&&V&&e)
56     {
57         for(int i=0;i<e;i++)
58         {
59             int x,y,z;
60             cin>>x>>y>>z;
61             G[x].push_back(edge(y,z));
62             G[y].push_back(edge(x,z));
63         }
64         dijkstra(1);
65         if(d[V]!=INF) cout<<d[V]<<endl;
66         else cout<<-10086<<endl;
67         for(int i=0;i<=V;i++) G[i].clear();
68     } 
69     return 0;
70 } 

 

posted @ 2019-03-16 10:18  VBL  阅读(140)  评论(0编辑  收藏  举报