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

相关推荐
CHHH_HHH3 分钟前
【C++】红黑树:比AVL树更实用的平衡二叉搜索树
开发语言·数据结构·c++·算法·stl
Lazionr8 分钟前
基础算法 | 模拟算法练习
c++·算法
_日拱一卒14 分钟前
LeetCode:17电话号码的字母组合
java·数据结构·算法·leetcode·职场和发展
醉颜凉17 分钟前
Scala自定义Monad实战:从理论到应用的完整指南
大数据·算法·scala
STY_fish_201221 分钟前
KMP-前缀函数
算法
feng_you_ying_li24 分钟前
Linux 之线程封装,线程的同步与互斥,互斥锁的介绍
linux·c++·算法
HZ·湘怡1 小时前
二叉树 2 堆
算法
wabs6669 小时前
关于贪心算法的思考
算法·贪心算法
社交怪人9 小时前
【判断大小】信息学奥赛一本通C语言解法(题号1043)
算法
Snasph9 小时前
GNU Make 用户手册(中文版)
服务器·算法·gnu