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

相关推荐
晚风醉蝶7 小时前
1-18-基数排序-RadixSort
python·算法·排序算法·基数排序
lch2011_yb7 小时前
CSP-J 2022 上升点列 题解
算法·深度优先
lvts_cs7 小时前
化工产业规划对城市发展的具体指导作用
算法·动态规划
AI服务老曹8 小时前
水位识别算法接入AI视频分析平台全流程与误报优化指南(附接口字段与排查表)
人工智能·算法·音视频
江畔柳前堤8 小时前
消息队列:从直觉到精通的完整认知地图
开发语言·人工智能·算法·机器学习·ruby on rails·scala
ai产品老杨8 小时前
明火识别算法接入AI视频分析平台全流程与误报优化指南(附接口字段与排查表)
人工智能·算法·音视频
讨厌吃蛋黄酥8 小时前
📚408数据结构|最短路径算法一篇彻底搞懂!BFS、Dijkstra、Floyd别再傻傻分不清了
算法
Escalating_xu9 小时前
【C++ string 上篇】从字符串基础到容量管理、迭代器与经典算法题
java·c++·算法
Keven_119 小时前
算法札记:ACM中将高精度算法融于题目的模板
算法·acm·精度
小七在进步9 小时前
数据结构:快速排序
数据结构·算法·排序算法