Dijkstra
https://www.cnblogs.com/fzl194/p/8728018.html
const int N = 1e5 + 5;
int mp[N][N];
int d[N];
bool vis[N];
int V; //顶点数
void dijkstra(int s)
{
fill(d, d + V, INF);
fill(vis, vis + V, false);
d[s] = 0;
while(1) {
int v = -1;
//从未选择的点中选一个距离最小的顶点
for (int i = 0; i < V; ++i) {
if (!vis[i] && (v == -1 || d[i] < d[v])) v = i;
}
if (v == -1) break;
vis[v] = 1;
for (int u = 0; u < V; ++u) {
d[u] = min(d[u], d[v] + mp[v][u]);
}
}
}
堆优化
priority_queue<pii > q;
struct Edge
{
int next, to, w;
}e[M];
inline void add(int x, int y, int z)
{
e[++tot].w = z;
e[tot].next = head[x];
e[tot].to = y;
head[x] = tot;
}
void dijkstra()
{
d[s] = 0;
q.push(mp(0, s));
while (!q.empty()) {
int x = q.top().second;
q.pop();
if (vis[x]) continue;
vis[x] = 1;
for (int i = head[x]; i; i = e[i].next) {
int y = e[i].to;
if (d[y] > d[x] + e[i].w) {
d[y] = d[x] + e[i].w;
q.push(mp(-d[y], y));
}
}
}
}
matlab
clc
clear all
function [d path] = dijkstra(A, s, t)
%Dijkstra最短算法实现, A为图的赋权邻接矩阵
%当输入参数含有s和t时, 求s到t的最短路
if nargin==2
flag=0;
elseif nargin==3
flag=1;
end
n=length(A);%节点数
for i=1:n
A(i,j)=inf;
end;
V=zeros(1,n);
D=zeros(1,n);
T=A+inf;
T(s,:)=A(s,:);
A(:,s)=inf
path =[];
for k=1:n-1
[p,q] = min(T);
q1=q;
[p,q] = min(p);
v(q)=q1(q);
if flag
[value,index] = min(temp);
visit(index) = 0;
%更新 如果经过index节点,从起点到每个节点的路径长度更小,则更新,记录前趋节点,方便后面回溯循迹
for k=1:n
if D(k)>D(index)+W(index,k)
D(k) = D(index)+W(index,k);
parent(k) = index;
end
end
end
distance = D(e);%最短距离
%回溯法 从尾部往前寻找搜索路径
t = e;
while t~=st && t>0
path =[t,path];
p=parent(t);t=p;
end
path =[st,path];%最短路径
end
Floyd
https://www.cnblogs.com/fzl194/p/8729340.html
void floyd()
{
for (int k = 0; k < n; ++k) {
for (int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
mp[i][j] = min(mp[i][j], mp[i][k] + mp[k][j]);
}
Bellman-Ford
https://www.cnblogs.com/fzl194/p/8728529.html
SPFA
https://www.cnblogs.com/fzl194/p/8728883.html
struct Edge
{
int next, to, w;
}edge[M];
void add(int x, int y, int z)
{
edge[++tot].next = head[x];
edge[tot].to = y;
edge[tot].w = z;
head[x] = tot;
}
void spfa()
{
queue<int> q;
for (int i = 1; i <= n; ++i) {
d[i] = INF;
vis[i] = 0;
}
q.push(s);
d[s] = 0, vis[s] = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
vis[u] = 0;
for (int i = head[u]; i; i = edge[i].next) {
int v = edge[i].to;
if (d[v] > d[u] + edge[i].w) {
d[v] = d[u] + edge[i].w;
if (!vis[v]) q.push(v), vis[v] = 1;
}
}
}
}