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

相关推荐
Rubisco..2 小时前
牛客周赛 Round 111
数据结构·c++·算法
兮山与2 小时前
算法8.0
算法
高山上有一只小老虎2 小时前
杨辉三角的变形
java·算法
Swift社区2 小时前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
hz_zhangrl2 小时前
CCF-GESP 等级考试 2025年9月认证C++四级真题解析
开发语言·c++·算法·程序设计·gesp·c++四级·gesp2025年9月
少许极端2 小时前
算法奇妙屋(六)-哈希表
java·数据结构·算法·哈希算法·散列表·排序
羊羊小栈2 小时前
基于「多模态大模型 + BGE向量检索增强RAG」的新能源汽车故障诊断智能问答系统(vue+flask+AI算法)
vue.js·人工智能·算法·flask·汽车·毕业设计·大作业
Da Da 泓2 小时前
shellSort
java·数据结构·学习·算法·排序算法
2013编程爱好者3 小时前
计算时间复杂度
c++·算法·排序算法
巴里巴气3 小时前
第15题 三数之和
数据结构·算法·leetcode