dijkstra算法用于求无负权边的最短路题型
dijkstra朴素做法, 适用于节点数较少的稠密图,时间复杂度为O(n^2)
#include <bits/stdc++.h>
using namespace std;
const int N = 510, M = 100010;
int e[M], w[M], ne[M], h[N], idx;
int dist[N];
bool st[N];
int n, m;
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
void dijkstra()
{
memset(dist, 0x3f, sizeof dist);
memset(st, false, sizeof st);
dist[1] = 0;
for (int k = 0; k < n; k ++ )
{
int t = -1;
for (int j = 1; j <= n; j ++)
if (!st[j] && (t == -1 || dist[j] < dist[t])) t = j;
st[t] = true;
for (int i = h[t]; ~i; i = ne[i] )
{
int j = e[i];
if (dist[j] > dist[t] + w[i] ) dist[j] = dist[t] + w[i];
}
}
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 0; i < m; i ++ )
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
dijkstra();
if (dist[n] == 0x3f3f3f3f) dist[n] = -1;
cout << dist[n];
return 0;
}
dijkstra堆优化,时间复杂度为O(mlongn),适用于稀疏图,当求解的图是稠密图时,其效率一般都不如朴素的dijkstra
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
const int N = 150010, M = 150010;
typedef pair<int, int> PII;
int e[M], w[M], ne[M], h[N], idx;
int dist[N];
bool st[N];
int n, m;
void add(int a, int b, int c) // 邻接表加边
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
void dijkstra()
{
priority_queue<PII, vector<PII>, greater<PII> > heap;
memset(dist, 0x3f, sizeof dist);
memset(st, false, sizeof st);
dist[1] = 0;
heap.push({0, 1});
while (heap.size())
{
PII a = heap.top();
heap.pop();
int u = a.y;
if (st[u]) continue;
st[u] = true;
for (int i = h[u]; ~i; i = ne[i] )
{
int j = e[i];
if (dist[j] > dist[u] + w[i])
{
dist[j] = dist[u] + w[i];
heap.push({dist[j], j});
}
}
}
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 0; i < m; i ++ )
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
dijkstra();
if (dist[n] == 0x3f3f3f3f) dist[n] = -1; // 从起点抵达不了终点
cout << dist[n];
return 0;
}