P4568 [JLOI2011]飞行路线 && 分层图最短路板子

目录说:我在右边

什么是分层图最短路:

分层图最短路是指在可以进行分层图的图上解决最短路问题。
一般模型是:
在图上,有k次机会可以直接通过一条边(权值为0),问起点与终点之间的最短路径。

解决的一般思路:

以这个题为例,给出了k次可以免费通过一个点的机会,
我们可以把原来的图垒在一起;
ex:

k = 1
1 2 3
2 3 4
3 1 2
4 2 1
4 3 6

我们在建完图之后再加上图中权值为0的边,很明显的分成了两层(若k = 1).

如果上边的那一层走到了下边,那就说明用了一次免费的机会.
那么我们就可以在这个图中跑最短路了。
最后的答案就是每一个n,n',n'' ... 中取一个最大值.

怎么建图:

用手建图

for (int i = 1, a, b, d; i <= m; i++) {
    a = read(), b = read(), d = read();
    add(a, b, d), add(b, a, d);//在原图上连边
    for (int j = 1; j <= k; j++) {
        add(a + (j - 1) * n, b + j * n, 0);//两层之间的连一条无边权的边
        add(b + (j - 1) * n, a + j * n, 0);//如果走了那么说明用了一次免费机会
        add(a + j * n, b + j * n, d);//在每一层图上连边
    add(b + j * n, a + j * n, d);
    }
}

code

#include <bits/stdc++.h>

#define N 110010
#define M 2100010
#define ll long long

using namespace std;
const int inf = 2147483647;
int n, m, k, s, t; bool vis[N];
int head[N], add_edge, dis[N];
struct qaq {
    int next, to, dis;
}edge[M];
struct node {
    int point, dist;
    bool operator < (const node &b) const {
        return dist > b.dist;
    }
}; 

int read() {
    int s = 0, f = 0; char ch = getchar();
    while (!isdigit(ch)) f |= (ch == '-'), ch = getchar();
    while (isdigit(ch)) s = s * 10 + (ch ^ 48), ch = getchar();
    return f ? -s : s;
}

void add(int from, int to, int dis) {
    edge[++add_edge].next = head[from];
    edge[add_edge].dis = dis;
    edge[add_edge].to = to;
    head[from] = add_edge;
}

void dijkstra(int s) {
    memset(dis, 127, sizeof dis);
    dis[s] = 0;
    priority_queue<node> q;
    q.push((node){s, 0});
    while (!q.empty()) {
        node fr = q.top(); q.pop();
        int x = fr.point;
        if (vis[x]) continue;
        vis[x] = 1;
        for (int i = head[x]; i; i = edge[i].next) {
            int to = edge[i].to;
            if (!vis[to] && dis[to] > dis[x] + edge[i].dis) {
                dis[to] = dis[x] + edge[i].dis;
                q.push((node){to, dis[to]});
            }
        } 
    }
}

void add_work() {
    s = read(), t = read();
    for (int i = 1, a, b, d; i <= m; i++) {
        a = read(), b = read(), d = read();
        add(a, b, d), add(b, a, d);
        for (int j = 1; j <= k; j++) {
            add(a + (j - 1) * n, b + j * n, 0);
            add(b + (j - 1) * n, a + j * n, 0);
            add(a + j * n, b + j * n, d);
            add(b + j * n, a + j * n, d);
        }
    }
    dijkstra(s);
}

int main() {
    n = read(), m = read(), k = read();
    add_work();
    int ans = inf;
    for (int i = t; i <= n * (k + 1); i += n)
        ans = min(ans, dis[i]);
    cout << ans;
}                   

注意事项

  • spfa:我死了
  • 注意算好空间开的范围

    这个题边集是\(500000\)的,\(K\)最多是\(10\),原图加两条边,其它层的图及层之间会加4条边,
    每次最多加\(42\)条边,所以边集要开到\((4∗10+2)∗50000=2100000\)
    每层图要多开\(n\)个点,所以点集是\(10000+10000∗10=110000\)的,注意都\(+10\)

猜你喜欢

转载自www.cnblogs.com/zzz-hhh/p/12183183.html