luoguP4568 [JLOI2011]飞行路线

https://www.luogu.org/problemnew/show/P4568

题目中 k 的大小只有 10,我们可以考虑建立分层图跑最短路

相同层中 a -> b 的权值仍为 val,不同层中 a -> b 的权值为 0,相当于免费乘坐了一次飞机

写一个最短路就可以啦

#include <bits/stdc++.h>
#define CIOS ios::sync_with_stdio(false);
#define For(i, a, b) for(register int i = a; i <= b; i++)
#define Forr(i, a, b) for(register int i = a; i >= b; i--)
using namespace std;

typedef unsigned long long ull;
typedef long long ll;

template <typename _T>
inline void read(_T &f) {
    f = 0; _T fu = 1; char c = getchar();
    while(c < '0' || c > '9') { if(c == '-') fu = -1; c = getchar(); }
    while(c >= '0' && c <= '9') { f = (f << 3) + (f << 1) + (c & 15); c = getchar(); }
    f *= fu;
}

template <typename T>
void print(T x) {
    if(x < 0) putchar('-'), x = -x;
    if(x < 10) putchar(x + 48);
    else print(x / 10), putchar(x % 10 + 48);
}

template <typename T>
void print(T x, char t) {
    print(x); putchar(t);
}

const int N = 4e5 + 5, M = 4e6 + 5;

struct Edge {
    int u, v, next, val;
}G[M];

int head[N];
int n, m, k, s, t, tot;

inline void addedge(int u, int v, int val) {
    G[++tot] = (Edge) {u, v, head[u], val}, head[u] = tot;
}

int dis[N];
priority_queue < pair <int, int> > Q;
void dij(int s) {
    memset(dis, 0x3f, sizeof(dis));
    dis[s] = 0; Q.push(make_pair(0, s));
    while(!Q.empty()) {
        pair <int, int> t = Q.top(); Q.pop();
        if(-t.first > dis[t.second]) continue;
        int u = t.second;
        for(register int i = head[u]; i; i = G[i].next) {
            int v = G[i].v;
            if(dis[v] > dis[u] + G[i].val) {
                dis[v] = dis[u] + G[i].val;
                Q.push(make_pair(-dis[v], v));
            }
        }
    }
}

int main() {
    read(n); read(m); read(k);
    read(s); read(t);
    while(m--) {
        int a, b, c;
        read(a); read(b); read(c);
        for(register int i = 1; i <= k + 1; i++) addedge((i - 1) * n + a, (i - 1) * n + b, c), addedge((i - 1) * n + b, (i - 1) * n + a, c);
        for(register int i = 1; i <= k; i++) addedge((i - 1) * n + a, i * n + b, 0), addedge((i - 1) * n + b, i * n + a, 0);
    }
    dij(s); int ans = 0x7fffffff;
    for(register int i = 1; i <= k + 1; i++) ans = min(ans, dis[(i - 1) * n + t]);
    cout << ans << endl;
    return 0;
}
posted @ 2018-10-28 18:01  LJC00118  阅读(148)  评论(0编辑  收藏  举报
/*
*/