百度地图导航 (最短路)

百度地图导航

题意

给出 n 个城市, m 个城市群,每个城市群包含多个城市(一个城市可能被包含在多个城市群中),现在要修路,在城市与城市之间修路,或在城市群间修路,如果在城市群间修路,等价于两个城市群的城市两两各修一条路,问从城市 s 到 t 的最短路。

分析

问题主要是处理城市群间的相连。先考虑将每个城市群抽象成一个整体,再考虑将整体分成两个点,对于一个城市群 a ,我们新增一个入口点 a1,一个出口点 a2,那么从 a1 连边到城市群里的所有点,距离为0,从城市群里所有点连边到 a2,距离为0 。对于另一个城市群 b ,把 b2 连边 a1,a2 连边 b1,花费为城市群间的花费,等价于这两个城市群连接起来了。

code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, int> P;
const int MAXN = 2e5 + 10;
const ll INF = 1e17;
int n, m;
struct edge {
    int to, cost;
};
vector<edge> G[MAXN];
vector<pair<int, int> > groupid;
ll d[MAXN];
void dijkstra(int s)
{
    priority_queue<P, vector<P>, greater<P> > que;
    fill(d, d + MAXN, INF);
    d[s] = 0;
    que.push(P(0, s));
    while(!que.empty())
    {
        P p = que.top();
        que.pop();
        int v = p.second;
        if(d[v] < p.first) continue;
        for(int i = 0; i < G[v].size(); i++)
        {
            edge e = G[v][i];
            if(d[e.to] > d[v] + e.cost)
            {
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to], e.to));
            }
        }
    }
}
int main() {
    cin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int k;
        cin >> k;
        groupid.push_back(pair<int, int>(n + 1, n + 2));
        for(int j = 0; j < k; j++) {
            int x;
            cin >> x;
            G[n + 1].push_back(edge{x, 0});
            G[x].push_back(edge{n + 2, 0});
        }
        n += 2;
    }
    int m1;
    cin >> m1;
    for(int i = 0; i < m1; i++) {
        int u, v, c;
        cin >> u >> v >> c;
        G[u].push_back(edge{v, c});
        G[v].push_back(edge{u, c});
    }
    int m2;
    cin >> m2;
    for(int i = 0; i < m2; i++) {
        int a, b, l;
        cin >> a >> b >> l;
        a--; b--;
        G[groupid[a].second].push_back(edge{groupid[b].first, l});
        G[groupid[b].second].push_back(edge{groupid[a].first, l});
    }
    int s, t;
    cin >> s >> t;
    dijkstra(s);
    if(d[t] == INF) d[t] = -1;
    cout << d[t] << endl;
    return 0;
}

转载于:https://www.cnblogs.com/ftae/p/6986333.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值