地铁耗时最短的线路

#include <bits/stdc++.h>
using namespace std;

struct Node {
    string name;            // 当前站点名称
    int cost;               // 起点到当前站点的总耗时
    vector<string> path;    // 起点到当前站点的路径
};

int main() {
    int n;
    cin >> n;

    string start, end; 
    cin >> start >> end;

    // 图的邻接表
    unordered_map<string, vector<pair<string, int>>> graph;

    string u, v;
    int time;
    while (cin >> u && u != "0000") {
        cin >> v >> time;
        graph[u].push_back({v, time});
        graph[v].push_back({u, time}); // 双向图
    }

    // Lambda 比较器
    auto cmp = [](const Node& n1, const Node& n2) {
        return n1.cost > n2.cost;
    };

    // 优先队列,使用 lambda 初始化
    priority_queue<Node, vector<Node>, decltype(cmp)> pq(cmp);

    // 起点初始化
    pq.push({start, 0, {start}});

    // 最短路径记录
    unordered_map<string, int> minCost;
    for (auto& it : graph) {
        minCost[it.first] = INT_MAX;
    }
    minCost[start] = 0;

    // Dijkstra 算法
    while (!pq.empty()) {
        Node cur = pq.top();
        pq.pop();

        string currStation = cur.name;
        int currCost = cur.cost;

        // 到达终点,输出路径
        if (currStation == end) {
            for (int i = 0; i < cur.path.size(); i++) {
                if (i > 0) cout << " ";
                cout << cur.path[i];
            }
            cout << endl;
            return 0;
        }

        // 遍历邻居
        for (auto& neighbor : graph[currStation]) {
            string nextStation = neighbor.first;
            int nextCost = neighbor.second;

            if (currCost + nextCost < minCost[nextStation]) {
                minCost[nextStation] = currCost + nextCost;
                vector<string> newPath = cur.path;
                newPath.push_back(nextStation);
                pq.push({nextStation, minCost[nextStation], newPath});
            }
        }
    }
    return 0;
}

### 使用Python调用高德地图API实现地铁路径规划 为了通过 Python 实现地铁路径规划,可以利用高德开放平台提供的路径规划 API。此 API 支持多种出行方式的路径查询,其中包括公交线路,而地铁作为城市公共交通的一部分也在此范围内。 下面是一个简单的例子展示如何构建请求并解析返回的数据: #### 构建HTTP GET 请求 首先定义 URL 和参数字典,其中 `origin` 表示出发位置坐标(经度,纬度),`destination` 是目的地的位置坐标,`key` 则是你申请得到的应用程序密钥,用于身份验证。对于地铁路径规划特别需要注意设置 `strategy=0` 参数表示优先选择乘坐地铁[^1]。 ```python import requests def get_subway_route(origin, destination, key): url = "https://restapi.amap.com/v3/direction/transit/integrated" params = { 'key': key, 'origin': origin, 'destination': destination, 'city': '', # 如果是在同一城市内可留空自动识别;跨城则需指定具体城市名称或adcode 'cityd': '', # 同上,针对终点城市的设定 'extensions': 'base', 'output': 'json', 'strategy': 0 # 地铁优先策略 } response = requests.get(url=url, params=params).json() return response ``` #### 解析JSON响应数据 当接收到服务器端传回的信息后,可以通过访问 JSON 对象中的特定字段获取所需的结果。例如提取推荐方案的第一条记录中有关于步行距离、预计耗时以及详细的行程描述等内容。 ```python def parse_response(response_json): routes = [] try: route_list = response_json['route']['transits'] for idx, transit in enumerate(route_list[:]): segments = [] for segment in transit["segments"]: if segment["instruction"] != "": segments.append({ "distance": f"{segment['duration']}分钟", "description": segment["instruction"] }) total_time = int(transit["duration"]) / 60 single_route_info = { "total_time": f'{int(total_time)}分钟', "details": segments } routes.append(single_route_info) return {"routes": routes} except KeyError as e: print(f"Error parsing json: {e}") return None ``` 上述代码片段展示了如何发起 HTTP 请求给高德地图服务接口,并处理其反馈信息以获得优的地铁路线建议。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值