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

相关推荐
我不会插花弄玉6 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴8 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David8 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
西西弗Sisyphus8 小时前
C++ explicit 关键字工程实践
开发语言·c++
Pniubi11 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK11 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
上海潭龙东海科技有限公司12 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
一拳一个呆瓜13 小时前
【STL】头文件:<cmath>
c++·stl
草莓熊Lotso13 小时前
【C++ 基于微服务的即时通讯系统】ElasticSearch 用户数据管理实现
linux·数据库·c++·elasticsearch·微服务·架构
慧都产品智能化14 小时前
Qt 开发 CAD/CAM 工序表的隐性成本分析
c++·qt·qt5·qt6.3