Skip to content

Commit 834afd4

Browse files
authored
[20251018] BOJ / G4 / 가장 먼 곳 / 설진영
1 parent e94075d commit 834afd4

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static class Edge {
7+
int to, cost;
8+
9+
Edge(int to, int cost) {
10+
this.to = to;
11+
this.cost = cost;
12+
}
13+
}
14+
15+
static int n, m;
16+
static List<Edge>[] graph;
17+
static int[] friends = new int[3];
18+
19+
public static void main(String[] args) throws IOException {
20+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
21+
StringTokenizer st;
22+
23+
n = Integer.parseInt(br.readLine());
24+
25+
st = new StringTokenizer(br.readLine());
26+
for (int i = 0; i < 3; i++) {
27+
friends[i] = Integer.parseInt(st.nextToken());
28+
}
29+
30+
graph = new ArrayList[n + 1];
31+
for (int i = 1; i <= n; i++) {
32+
graph[i] = new ArrayList<>();
33+
}
34+
35+
m = Integer.parseInt(br.readLine());
36+
for (int i = 0; i < m; i++) {
37+
st = new StringTokenizer(br.readLine());
38+
int d = Integer.parseInt(st.nextToken());
39+
int e = Integer.parseInt(st.nextToken());
40+
int l = Integer.parseInt(st.nextToken());
41+
42+
graph[d].add(new Edge(e, l));
43+
graph[e].add(new Edge(d, l));
44+
}
45+
46+
int[][] distances = new int[3][n + 1];
47+
for (int i = 0; i < 3; i++) {
48+
distances[i] = dijkstra(friends[i]);
49+
}
50+
51+
int maxMinDistance = -1;
52+
int resultLand = -1;
53+
54+
for (int land = 1; land <= n; land++) {
55+
int minDistance = Integer.MAX_VALUE;
56+
for (int i = 0; i < 3; i++) {
57+
minDistance = Math.min(minDistance, distances[i][land]);
58+
}
59+
60+
if (minDistance >= maxMinDistance) {
61+
maxMinDistance = minDistance;
62+
resultLand = land;
63+
}
64+
}
65+
66+
System.out.println(resultLand);
67+
}
68+
69+
static int[] dijkstra(int start) {
70+
int[] dist = new int[n + 1];
71+
Arrays.fill(dist, Integer.MAX_VALUE);
72+
dist[start] = 0;
73+
74+
PriorityQueue<Edge> pq = new PriorityQueue<>((a, b) -> a.cost - b.cost);
75+
pq.offer(new Edge(start, 0));
76+
77+
while (!pq.isEmpty()) {
78+
Edge current = pq.poll();
79+
int now = current.to;
80+
int nowCost = current.cost;
81+
82+
if (dist[now] < nowCost) continue;
83+
84+
for (Edge next : graph[now]) {
85+
int nextCost = nowCost + next.cost;
86+
87+
if (nextCost < dist[next.to]) {
88+
dist[next.to] = nextCost;
89+
pq.offer(new Edge(next.to, nextCost));
90+
}
91+
}
92+
}
93+
94+
return dist;
95+
}
96+
}
97+
```

0 commit comments

Comments
 (0)