0%

最短路

dijkstra 基于贪心思想,利用了三角不等式,因为全局最小值不可能再被其他节点更新

dijkstra 用于解决单源最短路问题

disjstra 用于解决非负权图问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1e6 + 100;
typedef pair<int,int> pii;

struct node {
int v;
int w;
};
vector<node> e[maxn];
int dis[maxn];
bool vis[maxn];
int pre[maxn];

void dijkstra(int s) {
priority_queue<pii, vector<pii>, greater<pii>> q;
memset(dis, inf, sizeof(dis));
dis[s] = 0;
q.push({dis[s], s});
while(!q.empty()) {
pii t = q.top();
q.pop();
int u = t.second;
if(vis[u])
continue;
vis[u] = true;
for(node x:e[u]) {
int v = x.v;
int w = x.w;
if(dis[v]>dis[u]+w) {
dis[v] = dis[u] + w;
pre[v] = u;
q.push({dis[v], v});
}
}
}
}

int main() {
int n, m, s;
cin >> n >> m >> s;
for (int i = 0;i<n;i++) {
pre[i] = -1;
}
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
e[u].push_back((node){v, w});
// e[v].push_back((node){u, w});
}
dijkstra(s);
for (int i = 1; i <= n;i++) {
cout << dis[i] << " ";
}
cout << endl;
}

最短路计数,假设一张无权图,边长为1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void dijkstra(int s) {
priority_queue<pii,vector<pii>,greater<pii>> q;
memset(dis, inf, sizeof(dis));
dis[s] = 0;
q.push({0, s});
cnt[s] = 1;
while(!q.empty()) {
pii tmp = q.top();
int u = tmp.second;
q.pop();
if(vis[u])
continue;
vis[u] = true;
for (int v:e[u]) {
if(dis[v]>dis[u]+1) {
dis[v] = dis[u] + 1;
cnt[v] = cnt[u];
if(!vis[v]) {
q.push({dis[v],v});
}
} else if(dis[v] == dis[u]+1) {
cnt[v] = (cnt[v] + cnt[u]) % mod;
}
}
}
}

SPFA
基于队列优化的Bellman-Ford算法