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

相关推荐
剑挑星河月8 分钟前
31.下一个排列
java·算法·leetcode
凌波粒11 分钟前
LeetCode--98.验证二叉搜索树(二叉树)
算法·leetcode·职场和发展
Kurisu57534 分钟前
深度拆解:从令牌桶到滑动窗口,高并发系统限流算法的数学本质与边界
java·网络·算法
哈泽尔都34 分钟前
运动控制教学——5分钟学会力控算法(阻抗/导纳/力位混合)
c++·python·算法·决策树·贪心算法·机器人·gpu算力
WWW652638 分钟前
代码随想录 打卡第四十七天
数据结构·算法·leetcode
cpp_250143 分钟前
P10722 [GESP202406 六级] 二叉树
数据结构·c++·算法·题解·洛谷·树形结构·gesp六级
smj2302_796826521 小时前
解决leetcode第3948题字典序最大的MEX数组
python·算法·leetcode
周末也要写八哥1 小时前
浅谈:C++中cpp 14 ~ cpp 17
开发语言·c++·算法
许彰午2 小时前
13_HashMap底层原理详解
算法·哈希算法
GIOTTO情2 小时前
基于 NLP 情感加权算法的智能舆情处置系统架构与落地实现
人工智能·算法·自然语言处理