zoukankan      html  css  js  c++  java
  • 链式前向星建图+SPFA求最短路

    #include <iostream>
    #include <cmath>
    #include <cstdlib>
    #include <cstring>
    #include <climits>
    #include <algorithm>
    #include <numeric>
    #include <utility>
    #include <random>
    #include <chrono>
    #include <string>
    #include <vector>
    #include <stack>
    #include <queue>
    #include <set>
    #include <map>
    #include <unordered_set>
    #include <unordered_map>
    
    using namespace std;
    
    using LL = long long;
    using ULL = unsigned long long;
    using PII = pair<int, int>;
    using PIL = pair<int, LL>;
    using PLL = pair<LL, LL>;
    // const int mod = 1e9 + 7;
    // const int mod = 998244353;
    
    inline void quickread() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    }
    
    const int maxn = 1e4 + 5;
    const int maxm = 5e5 + 5;
    const int inf = INT_MAX;
    int n, m, s;
    int nne;
    int head[maxn];
    
    struct Edge {
        int u, v, w;
        int nxt;
        Edge(int u = 0, int v = 0, int w = 0, int nxt = 0) : 
            u(u), v(v), w(w), nxt(nxt) {};
    }edge[maxm];
    
    void init() {
        memset(head, -1, sizeof(head));
        nne = 0;
    }
    
    void add_edge(int u, int v, int w) {
        edge[nne] = Edge(u, v, w, head[u]);
        head[u] = nne++;
    }
    
    
    
    int dis[maxn];
    bool vis[maxn];
    
    void build_graph() {
        cin >> n >> m >> s;
        init();
        for (int i = 0; i < m; ++i) {
            int u, v, w;
            cin >> u >> v >> w;
            add_edge(u, v, w);
        }
    }
    
    void spfa(int s) {
        for (int i = 1; i <= n; ++i) {
            dis[i] = inf;
            vis[i] = false;
        }
        dis[s] = 0;
        queue<int> q;
        q.push(s);
        vis[s] = true;
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            vis[u] = false;
            for (int e = head[u]; e != -1; e = edge[e].nxt) {
                int v = edge[e].v, w = edge[e].w;
                if (dis[u] + w < dis[v]) {
                    dis[v] = dis[u] + w;
                    if (!vis[v]) {
                        q.push(v);
                        vis[v] = true;
                    }
                }
            } 
        }
    }
    
    
    inline void work() {
        build_graph();
        spfa(s);
        for (int i = 1; i <= n; ++i) 
            cout << dis[i] << " ";
        cout << endl;
    }
    
    int main() {
        // freopen(".txt", "r", stdin);
        quickread();
        work();
        return 0;
    }
  • 相关阅读:
    linux命令大全
    【转载】nginx的五种负载算法
    nginx服务器安装及配置文件详解
    查看linux系统核数
    利用nginx实现分流
    ntohs, ntohl, htons,htonl的比较和详解
    Nginx反向代理之HTTP 请求头中的 X-Forwarded-For
    javascript中 for in 、for 、forEach 、for of 、Object.keys().
    vue里面路由传参的三种方式
    vue中ref在input中详解
  • 原文地址:https://www.cnblogs.com/betaa/p/13360125.html
Copyright © 2011-2022 走看看