5/31总结

· · 个人记录

Dijkstra の 优先队列优化

我们在写 Dijkstra 时,若节点数较少,我们可能会使用暴力枚举找最小的未被用于松弛的节点,它的复杂度是 O(n^2),并不适合 n 太大的场景。在稀疏图上,我们可以用一个优先队列来优化。

将距离作为关键字,使用最小堆,初始将原节点与对应距离距离 0 放入优先队列,每次取出队首,若对应的节点还没被用来松弛,则使用其松弛,并将松弛成功的节点与对应的当前距离放入优先队列,重复直到优先队列为空。它的正确性显而易见 ~,代码就不放了~。

对应的模版题:P4779 【模板】单源最短路径(标准版)

::::success[Code]

#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
struct node {
    int id, dis;
    bool operator<(const node &u) const {
        return dis > u.dis; //容器默认大根堆所以要反着来
    }
};
struct edge {
    int to, w;
};
int n, m, s, dis[(int)1e5+1];
bool vis[(int)1e5+1];
vector<edge> e[(int)1e5+1]; //vector存图
void dijkstra() {
    fill_n(dis + 1, n, 1e9);
    dis[s] = 0; //初始化
    priority_queue<node> q;
    q.push({s, 0});
    while(!q.empty()) {
        int top_id = q.top().id, top_dis = q.top().dis; //取出队首
        q.pop();
        if(vis[top_id]) { //若已经使用过则跳过
            continue;
        }
        vis[top_id] = true;
        for(const edge &ei : e[top_id]) {
            if(top_dis + ei.w < dis[ei.to]) {
                q.push({ei.to, dis[ei.to] = top_dis + ei.w}); //松弛
            }
        }
    }
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin >> n >> m >> s;
    while(m--) {
        int u_i, v_i, w_i;
        cin >> u_i >> v_i >> w_i;
        e[u_i].push_back({v_i, w_i}); //加边
    }
    dijkstra();
    for(int i = 1; i <= n; ++i) {
        cout << dis[i] << ' ';
    }
    return 0;
}

::::

P1144 最短路计数

由于本题边无权,用 BFS 和 Dijkstra 是差不多的。若用权为 w 的边由节点 pre 松弛 to 时发现 dis_{pre}+w \leq dis_{to},则将 to 的最短路数累加上 pre 的最短路数。

::::success[Code]

#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
struct node {
    int id, dis;
};
int n, m, dis[(int)1e6+1], sum[(int)1e6+1];
bool vis[(int)1e6+1];
vector<int> e[(int)1e6+1];
void bfs() {
    fill_n(dis + 2, n - 1, 1e8);
    sum[1] = 1;
    queue<node> q;
    q.push({1, 0}); //初始化
    while(!q.empty()) {
        if(!vis[q.front().id]) {
            vis[q.front().id] = true;
            for(int ei : e[q.front().id]) {
                if(q.front().dis + 1 <= dis[ei]) {
                    sum[ei] = (sum[ei] + sum[q.front().id]) % 100003; //累加,记得取余
                    if(q.front().dis + 1 < dis[ei]) {
                        q.push({ei, dis[ei] = q.front().dis + 1}); //松弛
                    }
                }
            }
        }
        q.pop();
    }
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin >> n >> m;
    while(m--) {
        int x, y;
        cin >> x >> y;
        e[x].push_back(y);
        e[y].push_back(x);
    }
    bfs();
    for(int i = 1; i <= n; ++i) {
        cout << sum[i] << '\n';
    }
    return 0;
}

::::