SPFA判负环

题目链接

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#define inf 0x3f3f3f3f
#include <queue>

using namespace std ;
const int N = 6e3 + 8 ;

int n, m ;
struct Edge {
	int to, w, next ;
} edge[N];

int dis[N], cnt[N] ;		
bool vis[N] ;
int head[N] ;
int tot ;

inline void init() {
	tot = 0 ;
	memset(vis, 0, sizeof(vis)) ;
	memset(dis, inf, sizeof(dis)) ;
	memset(cnt, 0, sizeof(cnt)) ;
	for (int i = 1 ; i <= n ; i ++) {
		head[i] = 0 ;
	}
}

inline void add(int u, int v, int w) {		//链式前向星存图
	edge[++tot].to = v ;
	edge[tot].w = w ;
	edge[tot].next = head[u] ;
	head[u] = tot ;
}

bool SPFA() {
	dis[1] = 0, vis[1] = true ;
	queue<int>Q ;
	Q.push(1) ;
	while (!Q.empty()) {
		int x = Q.front() ;
		Q.pop() ;
		vis[x] = false ;		//把这个点拿出来以后立刻改成未标记状态
		for (int i = head[x] ; i ; i = edge[i].next ) {
			int y = edge[i].to, z = edge[i].w ;
			if (dis[y] > dis[x] + z) {
				dis[y] = dis[x] + z ;
				if (!vis[y]) {
					Q.push(y) ;
					vis[y] = true ;
					if ( ++ cnt[y] > n)
						return true ;
				}
			}
		}
	}
	return false ;
}

int main() {
	std::ios::sync_with_stdio(false) ; 
	std::cin.tie(0) ;  
	
	int T ;
	cin >> T  ;
	while (T --) {
		init() ;
		cin >> n >> m ;
		while (m --) {
			int u, v, w ;
			cin >> u >> v >> w ;
			add(u, v, w ) ;
			if (w >= 0)
				add(v, u, w) ;
		}
		if (SPFA()) {
			cout << "YES" << '\n' ;
		} else
			cout << "NO" << '\n' ;
	}

	return 0 ;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值