范沐垚


私信TA

用户名:dotcpp0614554

访问量:4925

签 名:

好大喜功

等  级
排  名 194
经  验 6576
参赛次数 0
文章发表 87
年  龄 18
在职情况 学生
学  校 看今夜 小楼灯宴
专  业 尽是良辰美眷

  自我简介:

沽名钓誉

//利用spfa判断该图存不存在负环 
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>

using namespace std;
const int N=1e5+1;
int dis[N],e[N],ne[N],h[N],idx,w[N],cnt[N];//cnt存从起点到该点的边数 
bool st[N];
queue<int> q;
int n,m;

void add(int a,int b,int x)
{
	e[idx]=b,w[idx]=x,ne[idx]=h[a],h[a]=idx++;
}

int spfa()
{
	memset(dis,0x3f,sizeof dis);
	for(int i=1;i<=n;i++)      //不知道负环在哪个部位,因此所有点入队查询 
	{
		q.push(i);
		st[i]=true;
	}
	
	while(q.size())
	{
		auto t=q.front();
		q.pop();
		st[t]=false;
		
		for(int i=h[t];i!=-1;i=ne[i])
		{
			int j=e[i];
			if(dis[j]>dis[t]+w[i])
			{
				dis[j]=dis[t]+w[i];
				cnt[j]=cnt[t]+1;
				if(cnt[j]>=n)return 1;	//如果边数大于等于n,说明存在负环(在找最短路时,会死循环) 
				if(!st[j])
				{
					q.push(j);
					st[j]=true;
				}
			}
		}
	}
	return 0;
 } 

int main(void)
 {
 	cin>>n>>m;
 	memset(h,-1,sizeof h);
 	while(m--)
 	{
 		int a,b,c;
 		cin>>a>>b>>c;
 		add(a,b,c);
	 }
	 if(spfa())
	 puts("YES");
	 else
	 puts("NO");
	 return 0;
 }


 

0.0分

0 人评分

  评论区

  • «
  • »