
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
public static class Node {
int start;
int to;
int cost;
Node(int s, int t, int c) {
this.start = s;
this.to = t;
this.cost = c;
}
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
int TC = Integer.parseInt(br.readLine());
for (int test = 0; test < TC; test++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int W = Integer.parseInt(st.nextToken());
List<Node> graph = new ArrayList<>();
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
graph.add(new Node(start, to, cost));
graph.add(new Node(to, start, cost));
}
for (int i = 0; i < W; i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
graph.add(new Node(start, to, -cost));
}
boolean flag = bellmanFord(N, graph);
bw.write(flag ? "YES\n" : "NO\n");
}
br.close();
bw.close();
}
public static boolean bellmanFord(int N, List<Node> graph) {
int[] dist = new int[N + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[0] = 0;
for (int i = 1; i <= N; i++) {
graph.add(new Node(0, i, 0)); // add
}
for (int i = 0; i < N; i++) {
for (Node node : graph) {
if (dist[node.start] != Integer.MAX_VALUE && dist[node.to] > dist[node.start] + node.cost) {
dist[node.to] = dist[node.start] + node.cost;
}
}
}
for (Node node : graph) {
if (dist[node.start] != Integer.MAX_VALUE && dist[node.to] > dist[node.start] + node.cost) {
return true;
}
}
return false;
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 2638번: 치즈 (0) | 2025.10.06 |
|---|---|
| [JAVA-자바] 2206번: 벽 부수고 이동하기 (0) | 2025.05.22 |
| [JAVA-자바] 1238번: 파티 (0) | 2025.05.19 |
| [JAVA-자바] 17144번: 미세먼지 안녕! (0) | 2025.05.18 |
| [JAVA-자바] 14938번: 서강그라운드 (0) | 2025.05.16 |