朴素dijkstra:题目
当面对单源最短路问题时,若所有边均为正权,则可用Dijkstra算法求解。
思路:维护一个尚未确定到起点最短距离的点的集合,每次从该集合中选取一个到起点距离最短的点,则该点到起点的最短距离已近被确定,从该集合删除,并更新与该点相关的所有点距离(松弛操作)。
时间复杂度:O(n^2) ,n为点数。
#include <bits/stdc++.h>
using namespace std;
const int N = 510;
int dis[N];
int st[N];
int g[N][N];
int n, m;
int dijkstra()
{
dis[1] = 0;
for(int i = 1; i <= n; i++) {
int t = -1;
for(int j = 1; j <= n; j++) {
if(!st[j] && (t == -1 || dis[j] < dis[t])) {
t = j;
}
}
st[t] = true;
for(int j = 1; j <= n; j++) {
dis[j] = min(dis[j], dis[t] + g[t][j]);
}
}
return dis[n] == 0x3f3f3f3f? -1: dis[n];
}
int main()
{
memset(g, 0x3f, sizeof g);
memset(dis, 0x3f, sizeof dis);
cin >> n >> m;
for(int i = 0; i < m; i++) {
int x, y, z;
cin >> x >> y >> z;
g[x][y] = min(g[x][y], z);
}
cout << dijkstra();
return 0;
}
堆优化版dijkstra:题目
在朴素算法中,可发现在寻找距离最短的点时对图中所有点均进行了扫描,为此,可以借助小根堆,通过堆排直接获得距离最短的点。
时间复杂度:O(mlogn) ,n为点数,m为边数。
#include <bits/stdc++.h>
using namespace std;
const int N = 150010;
typedef pair<int, int> PII;
int idx, e[N], ne[N], w[N], h[N], dis[N];
bool st[N];
void add(int a, int b, int x) { // 不同于朴素dijkstra,在此使用邻接表
e[idx] = b;
ne[idx] = h[a];
w[idx] = x;
h[a] = idx++;
}
int dijkstra(int n)
{
memset(dis, 0x3f, sizeof dis);
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, 1});
while(heap.size()) {
int id = heap.top().second;
int distance = heap.top().first;
heap.pop();
if (st[id]) continue;
st[id] = true;
for (int i = h[id]; i != -1; i = ne[i])
{
int j = e[i];
if (dis[j] > distance + w[i]) {
dis[j] = distance + w[i];
heap.push({dis[j], j});
}
}
}
return dis[n] == 0x3f3f3f3f? -1 : dis[n];;
}
int main()
{
memset(h, -1, sizeof h);
int n, m;
cin >> n >> m;
while(m--) {
int x, y, z;
cin >> x >> y >> z;
add(x, y, z);
}
cout << dijkstra(n) << endl;
return 0;
}