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

相关推荐
10001hours1 天前
初阶数据结构.1.顺序表.通讯录项目(只有源码和注释)
数据结构·算法
Emilia486.1 天前
八大排序算法
算法·排序算法
blammmp1 天前
算法专题十九:记忆化搜索(暴搜->记忆化搜索)
算法·深度优先·记忆化搜索
MicroTech20251 天前
边缘智能的创新:MLGO微算法科技推出基于QoS感知的边缘大模型自适应拆分推理编排技术
科技·算法·ai
王哈哈^_^1 天前
【数据集】【YOLO】目标检测游泳数据集 4481 张,溺水数据集,YOLO河道、海滩游泳识别算法实战训练教程。
人工智能·算法·yolo·目标检测·计算机视觉·分类·视觉检测
巴里巴气1 天前
第73题 矩阵置零
线性代数·算法·矩阵
voice6701 天前
密码学实验二
算法·密码学·哈希算法
Blossom.1181 天前
把AI“编”进草垫:1KB决策树让宠物垫自己报「如厕记录」
java·人工智能·python·算法·决策树·机器学习·宠物
寂静山林1 天前
UVa 10989 Bomb Divide and Conquer
算法
极客数模1 天前
2025年(第六届)“大湾区杯”粤港澳金融数学建模竞赛准备!严格遵循要求,拿下大奖!
大数据·python·数学建模·金融·分类·图论·boosting