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

相关推荐
CoovallyAIHub13 分钟前
方案 | 动车底部零部件检测实时流水线检测算法改进
深度学习·算法·计算机视觉
CoovallyAIHub15 分钟前
方案 | 光伏清洁机器人系统详细技术实施方案
深度学习·算法·计算机视觉
lxmyzzs19 分钟前
【图像算法 - 14】精准识别路面墙体裂缝:基于YOLO12与OpenCV的实例分割智能检测实战(附完整代码)
人工智能·opencv·算法·计算机视觉·裂缝检测·yolo12
洋曼巴-young21 分钟前
240. 搜索二维矩阵 II
数据结构·算法·矩阵
楼田莉子2 小时前
C++算法题目分享:二叉搜索树相关的习题
数据结构·c++·学习·算法·leetcode·面试
pusue_the_sun2 小时前
数据结构——栈和队列oj练习
c语言·数据结构·算法··队列
大锦终2 小时前
【算法】模拟专题
c++·算法
Xの哲學3 小时前
Perf使用详解
linux·网络·网络协议·算法·架构
想不明白的过度思考者3 小时前
数据结构(排序篇)——七大排序算法奇幻之旅:从扑克牌到百亿数据的魔法整理术
数据结构·算法·排序算法
小七rrrrr3 小时前
动态规划法 - 53. 最大子数组和
java·算法·动态规划