跳到正文

个人记录

负环

flamefrag约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年4月27日
更新
2026年4月27日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

负环定义:

负环是指边权和为负数的环,所以边权和为正数的环就是正环。

为啥我们要专门去查负环呢??

因为有负环的,转的越久,路径越短。

所以我们要专门用一个函数来判断负环。

那我们该如何判断呢,其实我们只需要跑一个最短路,不过要注意,要多用一个数组,记录走过的个数,如果大于总数,说明有负环。

C++
bool spfa()
{
	queue<int>op;
	memset(vis,0,sizeof(vis));
	memset(cnt,0,sizeof(cnt));
	memset(dis,0x3f,sizeof(dis));
	dis[1]=cnt[1]=0;
	op.push(1);
	vis[1]=1;
	while(op.size())
	{
		int x=op.front();
		op.pop();
		vis[x]=0;
		for(auto u:nbr[x])
		{
			int y=u.y;
			int w=u.w;
			if(dis[x]+w<dis[y])
			{
				dis[y]=dis[x]+w;
				cnt[y]=cnt[x]+1;
				if(cnt[y]>=n)
				{
					return 1;
				}
				if(vis[y]==0)
				{
					vis[y]=1;
					op.push(y);
				}
			}
		}
	}
	return 0;
}

拉近距离

本题,他要我们算最短距离,但是我们可以发现。因为他是减,所以我们可以把它设为-的。

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
int n,m;
struct stu
{
	int y,w;
};
int vis[10009];
int dis[10009];
int cnt[10009];
vector<stu>nbr[10009];
bool spfa(int s)
{
	queue<int>op;
	memset(vis,0,sizeof(vis));
	memset(cnt,0,sizeof(cnt));
	memset(dis,0x3f,sizeof(dis));
	dis[s]=cnt[s]=0;
	op.push(s);
	vis[s]=1;
	while(op.size())
	{
		int x=op.front();
		op.pop();
		vis[x]=0;
		for(auto u:nbr[x])
		{
			int y=u.y;
			int w=u.w;
			if(dis[x]+w<dis[y])
			{
				dis[y]=dis[x]+w;
				cnt[y]=cnt[x]+1;
				if(cnt[y]>=n)
				{
					return 1;
				}
				if(vis[y]==0)
				{
					vis[y]=1;
					op.push(y);
				}
			}
		}
	}
	return 0;
}
signed main()
{
	cin>>n>>m;
	for(int i=1;i<=n;++i)
	{
		nbr[i].clear();
	}
	for(int i=1;i<=m;++i)
	{
		int u,v,w;
		cin>>u>>v>>w;
		nbr[u].push_back({v,-w});
	}
	int f1=spfa(1);
	int ans=dis[n];
	int f2=spfa(n);
	if(f1==1 || f2==1)
	{
		cout<<"Forever love"<<"\n";
	}
	else
	{
		cout<<min(ans,dis[1]);
	}
	return 0;
}
原文