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

原题

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;
}
相关推荐
全域智图1 小时前
元胞自动机(Cellular Automata, CA)
人工智能·算法·机器学习
珂朵莉MM1 小时前
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)解题报告 | 珂学家
人工智能·算法·职场和发展·深度优先·图论
独家回忆3641 小时前
每日算法-250601
数据结构·算法
YONYON-R&D1 小时前
DEEPSEEK帮写的STM32消息流函数,直接可用.已经测试
算法·消息流
AgilityBaby1 小时前
UE5打包项目设置Project Settings(打包widows exe安装包)
c++·3d·ue5·游戏引擎·unreal engine
Steve lu3 小时前
回归任务损失函数对比曲线
人工智能·pytorch·深度学习·神经网络·算法·回归·原力计划
蒙奇D索大3 小时前
【数据结构】图论核心算法解析:深度优先搜索(DFS)的纵深遍历与生成树实战指南
数据结构·算法·深度优先·图论·图搜索算法
ShiinaMashirol3 小时前
代码随想录打卡|Day50 图论(拓扑排序精讲 、dijkstra(朴素版)精讲 )
java·图论
让我们一起加油好吗3 小时前
【基础算法】高精度(加、减、乘、除)
c++·算法·高精度·洛谷
不会敲代码的灵长类3 小时前
机器学习算法-k-means
算法·机器学习·kmeans