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;
}

 

posted @ 2018-11-09 09:13  xayata  阅读(168)  评论(0编辑  收藏  举报