acwing算法提高之图论--SPFA找负环

目录

  • [1 介绍](#1 介绍)
  • [2 训练](#2 训练)

1 介绍

本专题用来记录使用spfa算法来求负环的题目。

2 训练

题目1904虫洞

C++代码如下,

cpp 复制代码
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

typedef pair<int, int> PII;

const int N = 510;
int n, m, w;
int dist[N], cnt[N];
bool st[N]; //st[i]表示结点i是否在队列中
vector<vector<PII>> g;

void spfa() {
    queue<int> q;
    for (int i = 1; i <= n; ++i) {
        q.push(i);
        st[i] = 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;
                cnt[b] = cnt[t] + 1;
                if (!st[b]) {
                    q.push(b);
                }
                
                if (cnt[b] >= n) {
                    cout << "YES" << endl;
                    return;
                }
            }
        }
    }
    cout << "NO" << endl;
    return;
}

int main() {
    int T;
    cin >> T;
    while (T--) {
        cin >> n >> m >> w;
        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);
            g[b].emplace_back(a, c);
        }
        for (int i = 0; i < w; ++i) {
            int a, b, c;
            cin >> a >> b >> c;
            g[a].emplace_back(b, -c);
        }
        
        memset(cnt, 0, sizeof cnt);
        spfa();
    }
    return 0;
}

题目2

相关推荐
知识浅谈27 分钟前
DeepSeek V4 和 GPT-5.5 在同一天发布了??我也很懵,但对比完我悟了
算法
DeepModel37 分钟前
通俗易懂讲透 Q-Learning:从零学会强化学习核心算法
人工智能·学习·算法·机器学习
田梓燊39 分钟前
力扣:19.删除链表的倒数第 N 个结点
算法·leetcode·链表
简简单单做算法2 小时前
基于GA遗传优化双BP神经网络的时间序列预测算法matlab仿真
神经网络·算法·matlab·时间序列预测·双bp神经网络
guygg883 小时前
利用遗传算法解决列车优化运行问题的MATLAB实现
开发语言·算法·matlab
武藤一雄3 小时前
19个核心算法(C#版)
数据结构·windows·算法·c#·排序算法·.net·.netcore
sali-tec3 小时前
C# 基于OpenCv的视觉工作流-章52-交点查找
图像处理·人工智能·opencv·算法·计算机视觉
yu85939584 小时前
MATLAB连续线性化模型预测控制(SL-MPC)
算法·机器学习·matlab
ytttr8734 小时前
基于ACADO工具包的自主车道跟踪与避障MPC控制
算法