acwing算法提高之图论--单源最短路的扩展应用

目录

  • [1 介绍](#1 介绍)
  • [2 训练](#2 训练)

1 介绍

本专题用来记录使用。。。。

2 训练

题目11137选择最佳线路

C++代码如下,

cpp 复制代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 1010, M = 20010;
int n, m;
int dist[N];
int st[N];
vector<vector<pair<int,int>>> g;
vector<int> snodes;
int enode; 
int w;

void spfa() {
    //cout << " ====== " << endl;
    
    memset(dist, 0x3f, sizeof dist);
    memset(st, 0, sizeof st);
    
    queue<int> q;
    for (auto snode : snodes) {
        //cout << "snode = " << snode << endl;
        dist[snode] = 0;
        q.push(snode);
        st[snode] = true; //已经在队列中了
    }
    
    while (!q.empty()) {
        auto t = q.front();
        q.pop();
        
        st[t] = false;
        
        for (auto [b, w] : g[t]) {
            if (dist[b] > dist[t] + w) {
                dist[b] = dist[t] + w;
                if (!st[b]) {
                    q.push(b);
                    st[b] = true;
                }
            }
        }
    }
    return;
}

int main() {
    while (cin >> n >> m >> enode) {
        g.clear();
        g.resize(n + 10);
        for (int i = 0; i < m; ++i) {
            int a, b, c;
            cin >> a >> b >> c;
            g[a].emplace_back(b, c);
        }
        
        cin >> w;
        snodes.resize(w);
        for (int i = 0; i < w; ++i) cin >> snodes[i];
        
        spfa();
        
        if (dist[enode] == 0x3f3f3f3f) cout << "-1" << endl;
        else cout << dist[enode] << endl;
    }
    
    return 0;
}

题目2

相关推荐
雾月552 小时前
LeetCode 941 有效的山脉数组
java·开发语言·数据结构·算法·leetcode·职场和发展
uhakadotcom3 小时前
归因工具:了解国内外顶级产品
算法·面试·github
小羊在奋斗5 小时前
【多源BFS】01 矩阵 / 飞地的数量 / 地图中的最高点 / 地图分析 / 腐烂的苹果
算法·矩阵·宽度优先
WG_175 小时前
图论:多源最短路
数据结构·c++·算法
一只小透明啊啊啊啊5 小时前
【leetcode 100】贪心Java版本
java·算法·leetcode
白白糖6 小时前
组合与括号生成(回溯)
python·算法·力扣
whltaoin6 小时前
动态规划算法深度解析:0-1背包问题(含完整流程)
算法·动态规划
好好学习^按时吃饭7 小时前
蓝桥杯2022年第十三届省赛真题-统计子矩阵
算法·蓝桥杯
Swift社区7 小时前
LeetCode 249 解法揭秘:如何把“abc”和“bcd”分到一组?
算法·leetcode·职场和发展
大萌神Nagato7 小时前
Johnson算法 流水线问题 java实现
java·算法