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

1 介绍

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

2 训练

题目11137选择最佳线路

C++代码如下,

#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;
}

题目21131拯救大兵瑞恩

C++代码如下,

#include <cstring>
#include <iostream>
#include <algorithm>
#include <deque>
#include <set>

#define x first
#define y second

using namespace std
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YMWM_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值