迪杰斯特拉算法
对于这个算法我用的是堆优化,其实到头来我还是为了投机取巧就看了这个堆优化的算法,这个算法是我好久之前看的了,现在又写是为了巩固一遍,这个迪杰斯特拉算法不能解决有负边的路径,对了还有个算法跟这个很像(普利姆算法),到时也会写出来。
代码如下:
#include<iostream>
#include<cstring>
#include<queue>
#include<vector>
#include<cstdio>
using namespace std;
const int maxn = 1e4 + 1;
const int INF = 0x3f3f3f3f; // 用来初始化每条边
int n, m; // n是顶点的个数, m 是边的个数
struct edge{
int to, cost; // 创建edge边节点,to用来存所到达的顶点,cost用来存边权
};
vector <edge> G[maxn]; //用来创建边表
typedef pair <int, int> P; // 第一位用来存最短距离,第二位用来存顶点
int d[maxn];
void dijkstra(int s){
priority_queue<P, vector <P>, greater<P> > que; //创建小顶堆
fill(d, d + n + 1, INF); //初始化边值
d[s] = 0;
que.push(P(0, s)); // 类似于广搜
while(!que.empty()){
P p = que.top(); que.pop();
int v = p.second;
if(d[v] < p.first)continue; // 如果后面还有到 v的点的边比前面更新的边的值要小就直接排除
for(int i = 0; i < G[v].size(); i++){
edge e = G[v][i];
if(d[e.to] > d[v] + e.cost){
d[e.to] = d[v] + e.cost;
que.push(P(d[e.to], e.to));
}
}
}
}
int main(){
scanf("%d%d", &n, &m);
int x, y, z; // x来存开始点, y来存所到达点, z来存权
for(int i = 0; i < m; i++){
scanf("%d%d%d", &x, &y, &z);
edge t, m;
t.cost = z; t.to = y;
m.cost = z; m.to = x;
G[x].push_back(t);
G[y].push_back(m);
}
dijkstra(1);
printf("%d\n", d[n]);
return 0;
}
上面的算法有些步骤我有注释