poj3259-BellmanFord判断负环模板

虫洞,判断负环,裸BellmanFord,没啥好说的
请注意,其实无论从哪个起点出发,只要走一遍bellman过程,最后得到的判断负环是否存在,是适用于全图的,并不是单单那个起点为首的环。

import java.io.BufferedInputStream;
import java.util.Scanner;

//bellman判负环
public class Main{
	static int[] dis;
	static int n;
	static int m;
	static int w;
	static int con;
	static private final int inf = 0x3f3f3f;
	static class Edge{
		int begin,end;
		int len;
	}

	static Edge[] edges;
	
	static boolean BellmanFord(int begin) {
		dis = new int[1000];
		for(int i=0;i<dis.length;i++) dis[i]=inf;
		dis[begin] = 0;
		
		
		for(int i=0;i<n-1;i++) {
			int f=0;
			for(int j=0;j<con;j++) {
				if(dis[edges[j].begin] + edges[j].len < dis[edges[j].end]) {
					dis[edges[j].end] = dis[edges[j].begin] + edges[j].len;	
					f=1;
				}
			}
			if(f==0) break;
		}
		
		
		for(int j=0;j<con;j++) 
			if(dis[edges[j].begin] + edges[j].len < dis[edges[j].end]) //有负环的存在
				return false;
			
		return true;
	}
	
	static void add(int begin,int end,int len) {
		edges[con] =  new Edge();
		edges[con].begin = begin; 
		edges[con].end = end;
		edges[con++].len = len; 
	}
	public static void main(String[] args) {
		Scanner sc  = new Scanner(new BufferedInputStream(System.in));
		 int test = sc.nextInt();
		 while(test-->0) {
			 n = sc.nextInt();
			 m= sc.nextInt();
			 w= sc.nextInt();
			 edges = new Edge[6000];
			 con= 0;
			 for(int i=0;i<m ;i++) {
				 int a = sc.nextInt(); int b =sc.nextInt() ;int c = sc.nextInt();
				 add(a,b,c);
				 add(b,a,c);
			 }
			 for(int i=0;i<w;i++) {
				 int a = sc.nextInt(); int b =sc.nextInt(); int c = sc.nextInt();
				 add(a,b,(-1)*c);
			 }
			 int  f=0;
			 for(int i=0;i<n;i++) {
				 if(BellmanFord(i)==false) {
					 System.out.println("YES");
					 f=1;
					 break;
				 }
			}
			 if(f==0) {
				 System.out.println("NO");
			 }
			 
		 }
		
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值