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

原题

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;
}
相关推荐
小安同学iter2 小时前
SQL50+Hot100系列(11.9)
算法·leetcode·职场和发展
uotqwkn89469s2 小时前
如果Visual Studio不支持C++14,应该如何解决?
c++·ide·visual studio
炼金士2 小时前
基于多智能体技术的码头车辆最快行驶路径方案重构
算法·路径规划·集装箱码头
Maple_land2 小时前
Linux复习:冯·诺依曼体系下的计算机本质:存储分级与IO效率的底层逻辑
linux·运维·服务器·c++·centos
ue星空2 小时前
UE核心架构概念
网络·c++·ue5
小刘max3 小时前
最长递增子序列(LIS)详解:从 dp[i] 到 O(n²) 动态规划
算法·动态规划
谢景行^顾4 小时前
数据结构知识掌握
linux·数据结构·算法
ShineWinsu4 小时前
对于数据结构:堆的超详细保姆级解析——下(堆排序以及TOP-K问题)
c语言·数据结构·c++·算法·面试·二叉树·
DuHz5 小时前
基于时频域霍夫变换的汽车雷达互干扰抑制——论文阅读
论文阅读·算法·汽车·毫米波雷达
_OP_CHEN5 小时前
C++进阶:(五)map系列容器的全面解析
开发语言·c++·map·红黑树·stl容器·键值对·mapoj题