#include<stdio.h>
#include<vector>
#include<queue>
#include<string.h>
#define inf 50000000000000ll
using namespace std;
typedef long long ll;
struct node
{
ll to,w;
node(){}
node(ll to,ll w)
{
this->to=to;
this->w=w;
}
};
ll n,m;
vector<node>vt[2005];
ll mark[2005],dist[2005];
ll flag,haha[2005];//haha用于记录点有没有走过
void DFS_SPFA(int u){//DFS优化的SPFA找负环
if(flag) return ;
haha[u]=1;
mark[u]=true;
for(int i=0;i<vt[u].size();i++)
{
if(flag) return ;
int v=vt[u][i].to;
if(dist[u]+vt[u][i].w<dist[v])
{
dist[v]=dist[u]+vt[u][i].w;
if(mark[v])
{
flag=true;
return ;
}
else DFS_SPFA(v);
}
}
mark[u]=false;
}
int main()
{
ll T;
scanf("%lld",&T);
while(T--)
{
flag=0;
scanf("%lld%lld",&n,&m);
for(ll i=1;i<=n;i++)vt[i].clear();
for(ll i=0;i<m;i++)
{
ll u,v,w;
scanf("%lld%lld%lld",&u,&v,&w);
vt[u].push_back(node(v,w));
}
memset(mark,0,sizeof(mark));
memset(haha,0,sizeof(haha));
for(ll i=1;i<=n;i++)//如果不是连通图
if(haha[i]==0)
DFS_SPFA(i);
if(flag)//有负环
printf("Yes\n");
else printf("No\n");
}
return 0;
}
DFS优化的SPFA找负环模板
最新推荐文章于 2022-04-28 20:08:50 发布