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

相关推荐
总爱写点小BUG29 分钟前
打印不同的三角形(C语言)
java·c语言·算法
yaoh.wang31 分钟前
力扣(LeetCode) 27: 移除元素 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
2401_8414956441 分钟前
【自然语言处理】中文 n-gram 词模型
人工智能·python·算法·自然语言处理·n-gram·中文文本生成模型·kneser-ney平滑
San301 小时前
从零到一:彻底搞定面试高频算法——“列表转树”与“爬楼梯”全解析
javascript·算法·面试
F_D_Z1 小时前
最长连续序列(Longest Consecutive Sequence)
数据结构·算法·leetcode
ss2731 小时前
Java并发编程:DelayQueue延迟订单系统
java·python·算法
JHC0000001 小时前
118. 杨辉三角
python·算法·面试
WolfGang0073211 小时前
代码随想录算法训练营Day50 | 拓扑排序、dijkstra(朴素版)
数据结构·算法
业精于勤的牙2 小时前
浅谈:算法中的斐波那契数(四)
算法
一直都在5722 小时前
数据结构入门:二叉排序树的删除算法
数据结构·算法