当前位置:网站首页>Dijkstra AcWing 850. Dijkstra求最短路 II
Dijkstra AcWing 850. Dijkstra求最短路 II
2022-07-02 09:43:00 【T_Y_F666】
Dijkstra AcWing 850. Dijkstra求最短路 II
原题链接
算法标签
最短路 Dijkstra
思路
代码
#include<bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int, int>PII;
const int N = 150005;
int n,m;
int dist[N];
// 稀疏图用邻接表来存
int h[N], w[N], e[N], ne[N], idx;
bool st[N];
void add(int a,int b,int c){
// 有重边也不要紧,假设1->2有权重为2和3的边,再遍历到点1的时候2号点的距离会更新两次放入堆中
// 这样堆中会有很多冗余的点,但是在弹出的时候还是会弹出最小值2+x(x为之前确定的最短路径),
// 并标记st为true,所以下一次弹出3+x会continue不会向下执行。
e[idx]=b;
w[idx]=c;
ne[idx]=h[a];
h[a]=idx++;
}
int dij(){
memset(dist, 0x3f , sizeof dist);
dist[1] = 0;
// 这里heap中为什么要存pair呢,首先小根堆是根据距离来排的,所以有一个变量要是距离,
// 其次在从堆中拿出来的时候要知道知道这个点是哪个点,不然怎么更新邻接点呢?所以第二个变量要存点。
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0,1});
while (heap.size()) {
auto t = heap.top();
heap.pop();
int ver = t.y,dis = t.x;
if(st[ver]){
continue;
}
st[ver] = true;
for(int i = h[ver]; ~i; i = ne[i]){
// i只是个下标,e中在存的是i这个下标对应的点。
int j = e[i];
if (dist[j] > dist[ver] + w[i]){
dist[j] = dist[ver] + w[i];
heap.push({dist[j], j});
}
}
}
if (dist[n] == 0x3f3f3f3f){
return -1;
}
return dist[n];
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
memset(h, -1, sizeof h);
while(m--){
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
cout<<dij()<<"\n";
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈
边栏推荐
- [FFH] little bear driver calling process (take calling LED light driver as an example)
- arcgis js 4. Add pictures to x map
- Deep Copy Event bus
- drools执行完某个规则后终止别的规则执行
- CDA数据分析——Excel数据处理的常见知识点归纳
- Calculate the maximum path sum of binary tree
- Post request body content cannot be retrieved repeatedly
- MySQL and PostgreSQL methods to grab slow SQL
- 2.6 using recursion and stack - [tower of Hanoi problem]
- LeetCode—剑指 Offer 59 - I、59 - II
猜你喜欢
随机推荐
kubeadm join时出现错误:[ERROR Port-10250]: Port 10250 is in use [ERROR FileAvailable--etc-kubernetes-pki
区间DP AcWing 282. 石子合并
Addition, deletion, modification and query of MySQL table (Advanced)
Introduction to CPU instruction set
怎样写一篇赏心悦目的英文数学论文
Map和Set
AI mid stage technology research
drools执行指定的规则
BOM DOM
There is a hidden danger in CDH: the exchange memory used by the process of this role is XX megabytes. Warning threshold: 200 bytes
Brush questions --- binary tree --2
Anti shake throttle
PR 2021 quick start tutorial, learn about the and functions of the timeline panel
AAAI 2022 | Peking University & Ali Dharma Institute: pruning and compression of pre training language model based on comparative learning
Intel internal instructions - AVX and avx2 learning notes
上传文件时,服务器报错:IOFileUploadException: Processing of multipart/form-data request failed. 设备上没有空间
drools动态增加、修改、删除规则
Drools executes string rules or executes a rule file
SparkContext: Error initializing SparkContext解决方法
防抖 节流











