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

原题

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 分钟前
KNN 算法中的各种距离:从原理到应用
人工智能·python·算法·机器学习·knn·k近邻算法·距离公式
guozhetao14 分钟前
【ST表、倍增】P7167 [eJOI 2020] Fountain (Day1)
java·c++·python·算法·leetcode·深度优先·图论
吃着火锅x唱着歌17 分钟前
LeetCode 611.有效三角形的个数
算法·leetcode·职场和发展
CHANG_THE_WORLD3 小时前
金字塔降低采样
算法·金字塔采样
不知天地为何吴女士5 小时前
Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法
小坏坏的大世界5 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
liulilittle6 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
励志要当大牛的小白菜8 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970448 小时前
力扣 hot100 Day56
算法·leetcode
PAK向日葵9 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试