分层图 最短路

分层图

​ 对于某些边可以进行一些操作的问题,我们可以将图复制成多分,每进行一次操作等价于从一张图走到另一张图,这样就可以不重不漏的囊括所有的情况了,通过最短路算法把答案跑出来了,因为相当于一个大图上面最最短路,最后只需要判断一下,最优解在哪张图上即可。

例题

题意

给定n个点m条边和k次操作,每次操作可以让某一条边上的权重除二,每条边只能被操作一次,不用使完所有的操作,问从1号点到n号点的最短距离是多少。

输入

一行 n, m, k。

m行 u, v, w, 表示u到v有一条权重为w的边

数据范围

1 ≤ K ≤ N ≤ 50 , M ≤ 1000 。 1\le K\le N \le 50, M \le 1000。 1KN50,M1000

1 ≤ u , v ≤ N , 2 ≤ w ≤ 2000 。 1\le u, v \le N, 2 \le w \le2000。 1u,vN,2w2000

保证w均为偶数,图中无自环、重边、且是联通的。

输出

输出一个整数表示 1 1 1号城市到 n n n号城市的最小用时

Code

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <cmath> 
#include <stack>
#include <iomanip>
#include <deque> 
#include <sstream>
#define x first
#define y second
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 1e6 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
    e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
int a[N];
int dist[N];
bool st[N];
int dijkstra() {
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    heap.push({0, 1});
    while (heap.size()) {
        auto t = heap.top();
        heap.pop();
        int ver = t.y;
        if (st[ver]) continue;
        st[ver] = true;
        for (int i = h[ver]; ~i; i = ne[i]) {
            int j = e[i];
            if (dist[j] > dist[ver] + w[i]) {
                dist[j] = dist[ver] + w[i];
                heap.push({dist[j], j});
            }
        } 
    }
    int res = INF;
    for (int i = 0; i <= k; i ++ )  res = min(res, dist[n + i * n]);
    return res;
}
int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    cin >> n >> m >> k;
    memset(h, -1, sizeof h);
    while (m --) {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c), add(b, a, c);
        for (int i = 1; i <= k; i ++ ) {
            add(a + (i - 1) * n, b + i * n, c / 2);
            add(b + (i - 1) * n, a + i * n, c / 2);
            add(a + i * n, b + i * n, c);
            add(b + i * n, a + i * n, c);
        }
    }
    cout << dijkstra() << endl;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值