求助Bellman-Ford
查看原帖
求助Bellman-Ford
530349
天空即为极限楼主2021/7/3 11:25
#include<bits/stdc++.h>
using namespace std;
#define inf 0x7fffffff
int n,m,dis[1000005];
int sum(int x,int y)
{
	if(x<=inf&&y<=inf)return x+y;
	return inf; 
}
struct node{
	int now,to,dis;
}k[100005];
int cnt=0;
void add(int a,int b,int c)
{
	k[++cnt].dis=c;
	k[cnt].now=a;
	k[cnt].to=b;
}
void abab(int a,int b,int c)
{
	add(a,b,c);
	if(c>=0) add(b,a,c);
}
bool bf()
{
	for(int i=1;i<=n;i++)
		dis[i]=inf;
	dis[1]=0;	
	for(int i=1;i<n;i++){
		for(int j=1;j<=cnt;j++){
			int to=k[j].to,d=k[j].dis;
			if(sum(dis[k[j].now],d)<dis[to])
				dis[to]=dis[k[i].now]+d;
		}
	}
	for(int i=1;i<=cnt;i++)
	{
		int to=k[i].to,d=k[i].dis;
		if(sum(dis[k[i].now],d)<dis[to])return true;
	}
	return false;
}
int main()
{
	int t,a,b,c;
	cin>>t;
	while(t--)
	{
		memset(k,0,sizeof(k));
		cin>>n>>m;
		cnt=0;
		for(int i=1;i<=m;i++){
			cin>>a>>b>>c;
			abab(a,b,c);
		}
		if(bf()==true) cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
	}
}
2021/7/3 11:25
加载中...