SPFA检测负权环

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using PII = pair<int,int>;
const int N = 2e5 + 10;
const ll INF = 1e9 + 7;

int n,m;
ll dist[N];
int cnt[N];
vector<PII>G[N];
bool enter[N];

bool spfa(int start)
{
	queue<int>q;
	dist[start] = 0;
	cnt[start] ++;
	enter[start] = 1;
	q.push(start);
	
	while(!q.empty())
	{
		int u = q.front();
		q.pop();
		enter[u] = 0;
		
		for(auto [v,dis]:G[u])
		{
			if(dist[v] > dist[u] + dis)
			{
				dist[v] = dist[u] + dis;
				q.push(v);
				cnt[v] ++;
				enter[v] = 1;
				if(cnt[v] >= n)return 0;
			}
		}
	}
	return 1;
}
int main()
{
	fill(dist,dist + N,INF);
	cin >>n >>m;
	for(int i = 1;i <= m;i ++)
	{
		int op,a,b,c;
		cin >>op >>a >>b;
		if(op == 1)
		{
			cin >> c;
			G[a].push_back({b,-c});
		}else if(op == 2)
		{
			cin >> c;
			G[b].push_back({a,c});
		}else{
			G[a].push_back({b,0});
			G[b].push_back({a,0});
		}
	}
	
	bool neg = true;
	for(int i = 1;i <= n;i ++)
	{
		if(dist[i] == INF)
		{
			neg = spfa(i);
			if(neg == 0)break;
		}
	}
//	for(int i = 1;i <= n;i ++)cout <<dist[i] <<" ";
//	cout <<endl;
	if(neg == 0)cout <<"No"<<endl;
	else cout <<"Yes"<<endl;
	return 0;
}

对于差分约束以不等式形式给出,用SPFA,否则要用带权并查集

练习:小K的农场

相关推荐
蒸蒸yyyyzwd10 分钟前
秋招学习笔记 day46
c++·八股
Cccp.1233 小时前
【leetcode】(七)前缀树和贪心算法
数据结构·leetcode·贪心算法
千里码aicood3 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
码匠许师傅3 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
做cv的小昊4 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له4 小时前
World-In-World: World Models in a Closed-Loop World
算法
无名猿4 小时前
new/delete 与 malloc/free:为什么绝对不能混用
c++·内存管理·现代c++·踩坑记录
Logic1016 小时前
C语言/数据结构位运算题解:异或XOR找出多任务下载器中的“独特下载速度“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
2601_962218616 小时前
C++中decltype关键字的实现
开发语言·c++