Dijkstra算法

https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

算法过程简述:

变量定义:一个点集point,pointtype邻接表类型,next保存相邻点编号,dis保存点到起点距离,vis标识访问标记。一个最小堆heap。用于快速求出当前可到达点里拥有最小估计距离的点。

初始化:读入图,建立邻接表,建立一个空堆,并将起点距离设为0,加入堆等待扩展。

迭代过程:每次从堆中取出一个拥有最小估计距离的点,该点打上访问标记,枚举其相邻点,如果该点之前没有被访问过,则计算其最小估计距离,并加入堆。直到堆中不存在点为止,此时每个点的dis量即为其到起点的最小估计距离。

 1 struct edgetype
 2 {
 3     int to;
 4     int len;
 5 };
 6 struct pointtype
 7 {
 8     int dis;
 9     vector<edgetype> next;
10     bool vis;
11 }point[100001];
12 int n,m,s,t;
13 struct com
14 {
15     bool operator ()(int& a,int& b)
16     {
17         return point[a].dis>point[b].dis;
18     }
19 };
20 priority_queue<int,vector<int>,com> heap;
21 void init()
22 {
23     scanf("%d%d%d%d",&n,&m,&s,&t);
24     for(int i=1;i<=n;i++)
25     {
26         point[i].dis=1000000000;
27         point[i].vis=false;
28         point[i].next.clear();
29     }
30     for(int i=1;i<=m;i++)
31     {
32         int x,y,z;
33         edgetype tmp;
34         scanf("%d%d%d",&x,&y,&z);
35         tmp.to=y;
36         tmp.len=z;
37         point[x].next.push_back(tmp);
38         tmp.to=x;
39         point[y].next.push_back(tmp);
40     }
41     while(!heap.empty())
42     {
43         heap.pop();
44     }
45     point[s].dis=0;
46     for(int i=1;i<=n;i++)
47     {
48         heap.push(i);
49     }
50     return;
51 }
52 void dijkstra()
53 {
54     while(!heap.empty())
55     {
56         int now=heap.top();
57         heap.pop();
58         point[now].vis=true;
59         vector<edgetype>::iterator it;
60         for(it=point[now].next.begin();it!=point[now].next.end();it++)
61         {
62             if(point[(*it).to].vis)
63             {
64                 continue;
65             }
66             point[(*it).to].dis=min(point[(*it).to].dis,point[now].dis+(*it).len);
67         }
68     }
69     return;
70 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值