|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.StringTokenizer; |
| 7 | + |
| 8 | +public class Main { |
| 9 | + private static BufferedReader br; |
| 10 | + private static StringBuilder sb; |
| 11 | + private static StringTokenizer st; |
| 12 | + private static int n; |
| 13 | + private static int m; |
| 14 | + private static int w; |
| 15 | + private static class Edge { |
| 16 | + int from; |
| 17 | + int to; |
| 18 | + int weight; |
| 19 | + public Edge(int from, int to, int weight) { |
| 20 | + this.from = from; |
| 21 | + this.to = to; |
| 22 | + this.weight = weight; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + private static ArrayList<Edge> edges; |
| 27 | + |
| 28 | + public static void main(String[] args) throws IOException { |
| 29 | + br = new BufferedReader(new InputStreamReader(System.in)); |
| 30 | + sb = new StringBuilder(); |
| 31 | + |
| 32 | + int tc = Integer.parseInt(br.readLine()); |
| 33 | + while (tc-- > 0) { |
| 34 | + st = new StringTokenizer(br.readLine()); |
| 35 | + n = Integer.parseInt(st.nextToken()); |
| 36 | + m = Integer.parseInt(st.nextToken()); |
| 37 | + w = Integer.parseInt(st.nextToken()); |
| 38 | + |
| 39 | + edges = new ArrayList<>(); |
| 40 | + for (int i = 0; i < m; i++) { |
| 41 | + st = new StringTokenizer(br.readLine()); |
| 42 | + int s = Integer.parseInt(st.nextToken()); |
| 43 | + int e = Integer.parseInt(st.nextToken()); |
| 44 | + int t = Integer.parseInt(st.nextToken()); |
| 45 | + edges.add(new Edge(s, e, t)); |
| 46 | + edges.add(new Edge(e, s, t)); |
| 47 | + } |
| 48 | + |
| 49 | + for (int i = 0; i < w; i++) { |
| 50 | + st = new StringTokenizer(br.readLine()); |
| 51 | + int s = Integer.parseInt(st.nextToken()); |
| 52 | + int e = Integer.parseInt(st.nextToken()); |
| 53 | + int t = Integer.parseInt(st.nextToken()); |
| 54 | + edges.add(new Edge(s, e, -t)); |
| 55 | + } |
| 56 | + if (bellmanFord()) { |
| 57 | + sb.append("YES\n"); |
| 58 | + } else { |
| 59 | + sb.append("NO\n"); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + System.out.print(sb.toString()); |
| 64 | + } |
| 65 | + |
| 66 | + private static boolean bellmanFord() { |
| 67 | + int[] dist = new int[n + 1]; |
| 68 | + for (int i = 1; i < n; i++) { |
| 69 | + for (Edge edge : edges) { |
| 70 | + if (dist[edge.to] > dist[edge.from] + edge.weight) { |
| 71 | + dist[edge.to] = dist[edge.from] + edge.weight; |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + for (Edge edge : edges) { |
| 76 | + if (dist[edge.to] > dist[edge.from] + edge.weight) { |
| 77 | + return true; |
| 78 | + } |
| 79 | + } |
| 80 | + return false; |
| 81 | + } |
| 82 | +} |
| 83 | +``` |
0 commit comments