Skip to content

Commit 41a8381

Browse files
authored
Merge pull request #394 from AlgorithmWithGod/lkhyun
[20250628] BOJ / G4 / 도시 분할 계획 / 이강현
2 parents 5a256c9 + 0518c01 commit 41a8381

File tree

1 file changed

+79
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)