分层图最短路

分层图最短路

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inf = 0x3f3f3f3f3f3f3f3f;
const int maxn=100005;
struct node1 {
    int u, v;
    ll w;

    bool operator<(const node1 &b) const {
        if (u == b.u && v == b.v) return w < b.w;
        if (u == b.u) return v < b.v;
        return u < b.u;
    }
}a[maxn*2];
struct node2{
    int v,next;
    ll w;
}e[maxn*2];

struct node3 {
    int x, y;
    ll dis;

    node3() {};

    node3(int _x, int _y, int _dis) : x(_x), y(_y), dis(_dis) {};

    bool operator<(const node3 &b) const {
        return dis > b.dis;
    }
};
int t,head[maxn],n,m,k;

void init(){
    t=0;
    memset(head,0, sizeof(head));
}

void add(int u,int v,ll w){
    t++;
    e[t].v=v;
    e[t].w=w;
    e[t].next=head[u];
    head[u]=t;
}
ll d[maxn][15];
bool vis[maxn][15];

void dijkstra() {
    memset(vis, 0, sizeof(vis));
    memset(d, 0x3f, sizeof(d));
    d[1][0] = 0;
    priority_queue<node3> q;
    q.push(node3(1, 0, 0));
    while (!q.empty()) {
        node3 tmp = q.top();
        q.pop();
        int x = tmp.x;
        int y = tmp.y;
        if (vis[x][y]) continue;
        vis[x][y] = 1;
        for (int i = head[x]; i; i = e[i].next) {
            int v = e[i].v;
            if (d[x][y] + e[i].w < d[v][y]) {
                d[v][y] = d[x][y] + e[i].w;
                q.push(node3(v, y, d[v][y]));
            }
            if (y + 1 <= k && d[x][y] < d[v][y + 1]) {
                d[v][y + 1] = d[x][y];
                q.push(node3(v, y + 1, d[v][y + 1]));
            }
        }
    }
}
int main() {
    int _;
    scanf("%d", &_);
    while (_--) {
        init();
        scanf("%d%d%d", &n, &m, &k);
        for (int i = 1; i <= m; i++) {
            scanf("%d%d%lld", &a[i].u, &a[i].v, &a[i].w);
        }
        sort(a + 1, a + m + 1);
        int preu = -1, prev = -1;
        for (int i = 1; i <= m; i++) {
            if (a[i].u != preu || a[i].v != prev) {
                add(a[i].u,a[i].v,a[i].w);
                preu = a[i].u;
                prev = a[i].v;
            }
        }
        dijkstra();
        ll ans = inf;
        for (int i = 0; i <= k; i++) ans = min(ans, d[n][i]);
        printf("%lld
", ans);
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/Accpted/p/11438454.html