查看原帖
1335720
TC_QD楼主2025/1/18 19:08
#include<bits/stdc++.h>
#define maxn 100010
using namespace std;
struct edge{
	int now,nxt,weight;
}edge[maxn];
int dis[maxn],inq[maxn],timer[maxn],head[maxn],tot;
inline int read()
{
	int x=0,f=1;
	char ch=getchar();
	while (ch>'9' || ch<'0')
	{
		if (ch=='-')
		{
			f=-1;
		}
		ch=getchar();
	}
	while (ch<='9'  && ch>='0')
	{
		x*=10,x+=ch-'0';
		ch=getchar();
	}
	return f*x;
}
inline bool SPFA(int n)
{
	memset(dis,0x3f,sizeof(dis));
	memset(inq, 0, sizeof(inq));
	memset(timer, 0, sizeof(timer));
	dis[1]=0;
	queue<int> q;
	q.push(1);
	inq[1]=true;
	while (!q.empty())
	{
		int prev=q.front();
		q.pop();
		inq[prev]=false;
		for (int e=head[prev];e;e=edge[e].nxt)
		{
			int now=edge[e].now;
			if (dis[now]>dis[prev]+edge[e].weight)
			{
				dis[now]=dis[prev]+edge[e].weight;
				timer[now]++;
				if (timer[now]>n)
				{
					return true;
				}
				if (!inq[now])
				{
					inq[now]=true;
					q.push(now);
				} 
			}
		}
	}
	return false;
}
inline void add(int u,int v,int w)
{
	edge[++tot].now=v;
	edge[tot].weight=w;
	edge[tot].nxt=head[u];
	head[u]=tot;
	return;
}
int main()
{
	int T=read();
	while (T--)
	{
		int n=read(),m=read();
		tot=0;
		while (m--)
		{
			int u=read(),v=read(),w=read();
			add(u,v,w);
		}
		if (SPFA(n))
		{
			cout<<"YES\n";
		}
		else
		{
			cout<<"NO\n";
		}
	}
	//system("pause");
	return 0;
}

思路已爆炸(

2025/1/18 19:08
加载中...