Skip to content

Commit 8b25957

Browse files
committed
[20250903] BOJ / G4 / 도시 분할 계획 / 김민진
1 parent 483c1b2 commit 8b25957

File tree

1 file changed

+113
-0
lines changed

1 file changed

+113
-0
lines changed
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.List;
6+
import java.util.PriorityQueue;
7+
import java.util.Queue;
8+
import java.util.StringTokenizer;
9+
10+
public class BJ_1647_도시_분할_계획 {
11+
12+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
13+
private static StringTokenizer st;
14+
15+
private static int N; // node
16+
private static int M; // edge
17+
private static int cnt;
18+
private static int ans;
19+
20+
private static int[] parents;
21+
22+
private static Queue<Node> pq;
23+
private static List<Node>[] graph;
24+
25+
private static class Node implements Comparable<Node> {
26+
int from;
27+
int to;
28+
int weight;
29+
30+
public Node(int from, int to, int weight) {
31+
this.from = from;
32+
this.to = to;
33+
this.weight = weight;
34+
}
35+
36+
@Override
37+
public int compareTo(Node o) {
38+
return Integer.compare(this.weight, o.weight);
39+
}
40+
}
41+
42+
private static StringTokenizer tokenize() throws IOException {
43+
return new StringTokenizer(br.readLine());
44+
}
45+
46+
private static int nextInt() {
47+
return Integer.parseInt(st.nextToken());
48+
}
49+
50+
public static void main(String[] args) throws IOException {
51+
init();
52+
sol();
53+
}
54+
55+
private static void init() throws IOException {
56+
st = tokenize();
57+
58+
N = nextInt();
59+
M = nextInt();
60+
cnt = 0;
61+
ans = 0;
62+
63+
pq = new PriorityQueue<>();
64+
while (M-- > 0) {
65+
st = tokenize();
66+
67+
int a = nextInt();
68+
int b = nextInt();
69+
int c = nextInt();
70+
71+
pq.add(new Node(a, b, c));
72+
}
73+
74+
parents = new int[N + 1];
75+
for (int i = 1; i <= N; i++) {
76+
parents[i] = i;
77+
}
78+
}
79+
80+
private static void sol() {
81+
while (!pq.isEmpty() && cnt < N - 2) {
82+
Node cur = pq.poll();
83+
84+
if (find(cur.from) == find(cur.to)) {
85+
continue;
86+
}
87+
union(cur.from, cur.to);
88+
cnt++;
89+
ans += cur.weight;
90+
}
91+
System.out.println(ans);
92+
}
93+
94+
private static void union(int a, int b) {
95+
int rootA = find(a);
96+
int rootB = find(b);
97+
98+
if (rootA < rootB) {
99+
parents[rootB] = rootA;
100+
} else {
101+
parents[rootA] = rootB;
102+
}
103+
}
104+
105+
private static int find(int a) {
106+
if (parents[a] == a) {
107+
return a;
108+
}
109+
return parents[a] = find(parents[a]);
110+
}
111+
112+
}
113+
```

0 commit comments

Comments
 (0)