Skip to content

Commit a682979

Browse files
authored
[20250319] BOJ / G4 / 도시 분할 계획 / 김수연
1 parent 9fd4608 commit a682979

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class boj1647 {
6+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
static StringTokenizer st;
8+
static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());}
9+
static int nextInt() {return Integer.parseInt(st.nextToken());}
10+
11+
static int N, M;
12+
static ArrayList<Node> roads;
13+
static int[] parent;
14+
15+
public static void main(String[] args) throws Exception {
16+
nextLine();
17+
N = nextInt();
18+
M = nextInt();
19+
int a, b, c, answer = 0;
20+
roads = new ArrayList<>();
21+
parent = new int[N+1];
22+
for (int i = 0; i < N+1; i++) parent[i] = i;
23+
for (int i = 0; i < M; i++) {
24+
nextLine();
25+
a = nextInt();
26+
b = nextInt();
27+
c = nextInt();
28+
roads.add(new Node(a,b,c));
29+
}
30+
31+
roads.sort((o1, o2) -> o1.c-o2.c);
32+
33+
int cnt = 0;
34+
for (Node road : roads) {
35+
if (cnt == N-2) break;
36+
if (find(road.a) != find(road.b)) {
37+
union(road.a, road.b);
38+
answer += road.c;
39+
cnt++;
40+
}
41+
}
42+
System.out.println(answer);
43+
}
44+
45+
static void union(int a, int b) {
46+
int A = find(a);
47+
int B = find(b);
48+
if (A==B) return;
49+
if (A<B) parent[B] = A;
50+
else parent[A] = B;
51+
}
52+
53+
static int find(int node) {
54+
if (parent[node] == node) return node;
55+
return parent[node] = find(parent[node]);
56+
}
57+
58+
static class Node{
59+
int a, b, c;
60+
public Node(int a, int b, int c) {
61+
this.a = a;
62+
this.b = b;
63+
this.c = c;
64+
}
65+
}
66+
}
67+
68+
```

0 commit comments

Comments
 (0)