https://www.acmicpc.net/problem/1865
true
를 반환토록 로직 구성YES
에 해당import static java.lang.Integer.parseInt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
public class Main {
static int[] parent;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = parseInt(br.readLine());
List<String> answers = new ArrayList<>();
while (T-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int N = parseInt(st.nextToken());
int M = parseInt(st.nextToken());
int W = parseInt(st.nextToken());
parent = new int[N + 1];
Arrays.fill(parent, -1);
List<Edge> edges = new ArrayList<>();
while (M-- > 0) {
st = new StringTokenizer(br.readLine());
int u = parseInt(st.nextToken());
int v = parseInt(st.nextToken());
int w = parseInt(st.nextToken());
edges.add(new Edge(u, v, w));
edges.add(new Edge(v, u, w));
union(u, v);
}
while (W-- > 0) {
st = new StringTokenizer(br.readLine());
int u = parseInt(st.nextToken());
int v = parseInt(st.nextToken());
int w = parseInt(st.nextToken());
edges.add(new Edge(u, v, -w));
union(u, v);
}
List<Integer> parents = new ArrayList<>();
for (int i = 1; i < parent.length; i++) {
if (parent[i] < 0) {
parents.add(i);
}
}
List<Boolean> results = parents.stream().map(start -> isCycleExists(start, N, edges))
.filter(result -> result)
.collect(Collectors.toList());
answers.add(results.isEmpty() ? "NO" : "YES");
}
System.out.println(answers.stream().collect(Collectors.joining("\n")));
br.close();
}
static int find(int u) {
if (parent[u] < 0) {
return u;
}
return parent[u] = find(parent[u]);
}
static void union(int u, int v) {
int p1 = find(u);
int p2 = find(v);
if (p1 == p2) {
return;
}
if (parent[p1] < parent[p2]) {
parent[p1] += parent[p2];
parent[p2] = p1;
} else {
parent[p2] += parent[p1];
parent[p1] = p2;
}
}
static boolean isCycleExists(int start, int N, List<Edge> edges) {
int[] dist = new int[N + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
for (int i = 0; i < N - 1; i++) {
for (Edge e : edges) {
if (dist[e.u] != Integer.MAX_VALUE && dist[e.v] > dist[e.u] + e.w) {
dist[e.v] = dist[e.u] + e.w;
}
}
}
for (Edge e : edges) {
if (dist[e.u] != Integer.MAX_VALUE && dist[e.v] > dist[e.u] + e.w) {
return true;
}
}
return false;
}
static class Edge {
int u, v, w;
public Edge(int u, int v, int w) {
this.u = u;
this.v = v;
this.w = w;
}
}
}