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的农场

相关推荐
黑屋里的马1 天前
java的设计模式之桥接模式(Bridge)
java·算法·桥接模式
z187461030031 天前
list(带头双向循环链表)
数据结构·c++·链表
sin_hielo1 天前
leetcode 1611
算法·leetcode
李小白杂货铺1 天前
识别和破除信息茧房
算法·信息茧房·识别信息茧房·破除信息茧房·算法推荐型茧房·观点过滤型茧房·茧房
来荔枝一大筐1 天前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
报错小能手1 天前
C++笔记——STL list
c++·笔记
T.Ree.1 天前
cpp_list
开发语言·数据结构·c++·list
laocooon5238578861 天前
C++ 图片加背景音乐的处理
开发语言·c++
apocelipes1 天前
POSIX兼容系统上read和write系统调用的行为总结
linux·c语言·c++·python·golang·linux编程
暴风鱼划水1 天前
算法题(Python)数组篇 | 6.区间和
python·算法·数组·区间和