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

相关推荐
不知天地为何吴女士1 小时前
Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法
小坏坏的大世界1 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
励志要当大牛的小白菜4 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970444 小时前
力扣 hot100 Day56
算法·leetcode
PAK向日葵5 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱喝矿泉水的猛男7 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao7 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
YouQian7727 小时前
Traffic Lights set的使用
算法
go54631584659 小时前
基于深度学习的食管癌右喉返神经旁淋巴结预测系统研究
图像处理·人工智能·深度学习·神经网络·算法
aramae9 小时前
大话数据结构之<队列>
c语言·开发语言·数据结构·算法