Skip to content

Commit 560f3ed

Browse files
authored
[20251014] BOJ / G4 / 도시 분할 계획 / 이인희
1 parent 07575ad commit 560f3ed

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
private static int N, M;
7+
private static int[] Parent;
8+
private static List<Edge> Edges = new ArrayList<>();
9+
10+
private static class Edge implements Comparable<Edge> {
11+
int from, to, cost;
12+
Edge(int from, int to, int cost) {
13+
this.from = from;
14+
this.to = to;
15+
this.cost = cost;
16+
}
17+
@Override
18+
public int compareTo(Edge e) {
19+
return this.cost - e.cost;
20+
}
21+
}
22+
23+
public static void main(String[] args)throws IOException{
24+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
25+
StringTokenizer st = new StringTokenizer(br.readLine());
26+
N = Integer.parseInt(st.nextToken());
27+
M = Integer.parseInt(st.nextToken());
28+
Parent = new int[N+1];
29+
30+
31+
for(int i=1; i<=N; i++){
32+
Parent[i] = i;
33+
}
34+
35+
for(int i=0; i<M; i++){
36+
st = new StringTokenizer(br.readLine());
37+
int from = Integer.parseInt(st.nextToken());
38+
int to = Integer.parseInt(st.nextToken());
39+
int cost = Integer.parseInt(st.nextToken());
40+
Edges.add(new Edge(from, to,cost));
41+
}
42+
43+
Collections.sort(Edges);
44+
int answer = 0;
45+
int countOfEdge = 0;
46+
47+
for(Edge e : Edges){
48+
if(countOfEdge == N-2)
49+
break;
50+
if(union(e.from,e.to)){
51+
answer += e.cost;
52+
countOfEdge++;
53+
}
54+
}
55+
56+
System.out.println(answer);
57+
br.close();
58+
}
59+
60+
private static boolean union(int a, int b){
61+
a = find(a);
62+
b = find(b);
63+
if(a==b)
64+
return false;
65+
Parent[b] = a;
66+
return true;
67+
}
68+
69+
private static int find(int x){
70+
if(Parent[x]==x){
71+
return x;
72+
73+
}
74+
Parent[x] = find(Parent[x]);
75+
return Parent[x];
76+
}
77+
78+
}
79+
80+
```

0 commit comments

Comments
 (0)