• 50: Luogu P4568 分层图


    分层图最短路模板

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <ctime>
    #include <queue>
    #include <cstring>
    
    using namespace std;
    
    const int M = 2e6 + 5e5 + 10;
    
    #define gc getchar()
    inline int read() {
        int x = 0, f = 1; char c = gc;
        while(c < '0' || c > '9') {if(c == '-') f = -1; c = gc;}
        while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = gc;
        return x * f;
    }
    
    int dis[M], head[M], cnt, vis[M];
    struct Node {
        int u, v, nxt, w;
    } G[M];
    
    struct Node1 {
        int u, dis;
        bool operator < (const Node1 a) const {
            return this->dis > a.dis;
        }
    };
    
    priority_queue <Node1> Q;
    
    int n, m, k;
    int s, t;
    
    void Link(int u, int v, int w) {
        G[++ cnt].v = v; G[cnt].u = u; G[cnt].w = w; G[cnt].nxt = head[u]; head[u] = cnt;
    }
    
    void Dijkstra() {
        memset(dis, 0x3f, sizeof dis);
        Q.push((Node1){s, 0});
        dis[s] = 0;
        while(!Q.empty()) {
            Node1 tp = Q.top();
            Q.pop();
            if(vis[tp.u]) continue;
            vis[tp.u] = 1;
            for(int i = head[tp.u]; ~ i; i = G[i].nxt) {
                int v = G[i].v;
                if(dis[v] > dis[tp.u] + G[i].w) {
                    dis[v] = dis[tp.u] + G[i].w;
                     Q.push((Node1) {v, dis[v]});
                }
            }
        }
    }
    
    int main() {
        n = read(), m = read(), k = read();
        for(int i = 1; i <= n * k + n; i ++) head[i] = -1;
        s = read() + 1, t = read() + 1;
        for(int i = 1; i <= m; i ++) {
            int u = read() + 1, v = read() + 1, w = read();
            for(int j = 0; j < k; j ++) {
                Link(j * n + u, j * n + v, w);
                Link(j * n + v, j * n + u, w);
                Link(j * n + u, (j + 1) * n + v, 0);
                Link(j * n + v, (j + 1) * n + u, 0);
            }
            Link(n * k + u, n * k + v, w);
            Link(n * k + v, n * k + u, w);
        }
        Dijkstra();
        int Ans = (1 << 30);
        for(int i = 0; i <= k; i ++) {
            Ans = min(Ans, dis[i * n + t]);
        }
        cout << Ans;
        return 0;
    }
  • 相关阅读:
    数据结构3——图
    数据结构2——树
    数据结构1——堆栈和队列
    最大流——Dinic算法
    最大流——EK算法
    网络流——poj1273(入门)
    网络流(进阶)
    网络流
    并查集——poj1182(带权并查集高阶)
    并查集——poj1308(并查集延伸)
  • 原文地址:https://www.cnblogs.com/shandongs1/p/9933195.html
Copyright © 2020-2023  润新知