|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + public static void main(String[] args) throws IOException { |
| 8 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 9 | + int TC = nextInt(new StringTokenizer(br.readLine())); |
| 10 | + |
| 11 | + while (TC-- > 0) { |
| 12 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 13 | + int N = nextInt(st); |
| 14 | + int M = nextInt(st); |
| 15 | + int W = nextInt(st); |
| 16 | + |
| 17 | + List<Edge>[] graph = new ArrayList[N + 1]; |
| 18 | + for (int i = 1; i <= N; i++) { |
| 19 | + graph[i] = new ArrayList<>(); |
| 20 | + } |
| 21 | + |
| 22 | + for (int i = 0; i < M; i++) { |
| 23 | + st = new StringTokenizer(br.readLine()); |
| 24 | + int s = nextInt(st); |
| 25 | + int e = nextInt(st); |
| 26 | + int t = nextInt(st); |
| 27 | + |
| 28 | + graph[s].add(new Edge(e, t)); |
| 29 | + graph[e].add(new Edge(s, t)); |
| 30 | + } |
| 31 | + |
| 32 | + for (int i = 0; i < W; i++) { |
| 33 | + st = new StringTokenizer(br.readLine()); |
| 34 | + int s = nextInt(st); |
| 35 | + int e = nextInt(st); |
| 36 | + int t = nextInt(st); |
| 37 | + |
| 38 | + graph[s].add(new Edge(e, -t)); |
| 39 | + } |
| 40 | + |
| 41 | + if (hasNegativeCycle(graph, N)) { |
| 42 | + System.out.println("YES"); |
| 43 | + } else { |
| 44 | + System.out.println("NO"); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + static boolean hasNegativeCycle(List<Edge>[] graph, int N) { |
| 50 | + long[] dist = new long[N + 1]; |
| 51 | + final long INF = 987654321 |
| 52 | + Arrays.fill(dist, INF); |
| 53 | + |
| 54 | + for (int start = 1; start <= N; start++) { |
| 55 | + if (dist[start] != INF) continue; |
| 56 | + |
| 57 | + dist[start] = 0; |
| 58 | + |
| 59 | + boolean updated = false; |
| 60 | + for (int i = 0; i < N - 1; i++) { |
| 61 | + updated = false; |
| 62 | + for (int j = 1; j <= N; j++) { |
| 63 | + if (dist[j] == INF) continue; |
| 64 | + |
| 65 | + for (Edge edge : graph[j]) { |
| 66 | + if (dist[j] + edge.cost < dist[edge.to]) { |
| 67 | + dist[edge.to] = dist[j] + edge.cost; |
| 68 | + updated = true; |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + if (!updated) break; |
| 73 | + } |
| 74 | + |
| 75 | + for (int j = 1; j <= N; j++) { |
| 76 | + if (dist[j] == INF) continue; |
| 77 | + |
| 78 | + for (Edge edge : graph[j]) { |
| 79 | + if (dist[j] + edge.cost < dist[edge.to]) { |
| 80 | + return true; |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + return false; |
| 87 | + } |
| 88 | + |
| 89 | + static class Edge { |
| 90 | + int to, cost; |
| 91 | + |
| 92 | + Edge(int to, int cost) { |
| 93 | + this.to = to; |
| 94 | + this.cost = cost; |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + static int nextInt(StringTokenizer st) { |
| 99 | + return Integer.parseInt(st.nextToken()); |
| 100 | + } |
| 101 | +} |
| 102 | +``` |
0 commit comments