算法——图论——交通枢纽

原题

cpp 复制代码
#include <iostream>
#include <vector>
#include <queue>


using namespace std;
typedef pair<int, int> PII;

vector<PII> graph[100];
vector<vector<int>> Dist(100, vector<int>(100, -1));
vector<bool> State(100, false);

void Dijkstra(int s, int n) {
    for (int i = 0; i < n; ++i) {
        State[i] = false;
    }

    Dist[s][s] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> pq;
    pq.emplace(0, s);

    while (!pq.empty()) {
        pair<int, int> cur = pq.top();
        pq.pop();

        if (State[cur.second]) continue;
        else State[cur.second] = true;

        for (auto neighbor: graph[cur.second]) {
            if (Dist[s][neighbor.first] == -1 || Dist[s][neighbor.first] > Dist[s][cur.second] + neighbor.second) {
                Dist[s][neighbor.first] = Dist[s][cur.second] + neighbor.second;
                pq.emplace(Dist[s][neighbor.first], neighbor.first);
            }
        }
    }
}

int main() {

    int n, m, k;
    cin >> n >> m >> k;
    for (int i = 0; i < m; ++i) {
        int u, v, w;
        cin >> u >> v >> w;
        graph[u].emplace_back(v, w);
        graph[v].emplace_back(u, w);
    }
    int cityNum;
    vector<int> cityList;
    while (cin >> cityNum) {
        cityList.push_back(cityNum);
    }

    for (int city: cityList) {
        Dijkstra(city, n);
    }

    int sum = -1, resultCity;
    for (int i = 0; i < cityList.size(); ++i) {
        int tmp = 0;
        for (int j = 0; j < n; ++j) {
            tmp += Dist[cityList[i]][j];
        }
        if (sum == -1 || tmp < sum) {
            sum = tmp;
            resultCity = cityList[i];
        }
    }
    cout << resultCity << " " << sum << endl;
    return 0;
}
相关推荐
君义_noip5 分钟前
信息学奥赛一本通 1615:【例 1】序列的第 k 个数
c++·算法·信息学奥赛·csp-s
ホロHoro5 分钟前
数据结构非线性部分(1)
java·数据结构·算法
Blossom.1188 分钟前
大模型推理优化实战:连续批处理与PagedAttention性能提升300%
大数据·人工智能·python·神经网络·算法·机器学习·php
AA陈超12 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P07-19.发送鼠标光标数据
c++·笔记·学习·游戏·ue5·虚幻引擎
沉下去,苦磨练!17 分钟前
实现二维数组反转
java·数据结构·算法
bybitq24 分钟前
Leetcode-3780-Python
python·算法·leetcode
如何原谅奋力过但无声25 分钟前
【力扣-Python-75】颜色分类(middle)
python·算法·leetcode
玖剹26 分钟前
哈希表相关题目
数据结构·c++·算法·leetcode·哈希算法·散列表
laocooon52385788639 分钟前
相对名次算法的处理python
开发语言·python·算法
lixinnnn.1 小时前
bfs: kotori和迷宫
算法·宽度优先