虫洞,判断负环,裸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");
}
}
}
}