Skip to content

Commit 3b4a163

Browse files
authored
[20250902] BOJ / G3 / 나만 안되는 연애 / 이인희
1 parent 9020ba4 commit 3b4a163

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
```java
2+
import java.io.BufferedReader;
3+
import java.io.IOException;
4+
import java.io.InputStreamReader;
5+
import java.util.ArrayList;
6+
import java.util.PriorityQueue;
7+
import java.util.StringTokenizer;
8+
9+
public class Main {
10+
private static BufferedReader br;
11+
private static int n;
12+
private static int m;
13+
private static char[] genders;
14+
private static ArrayList<Edge>[] graph;
15+
16+
private static class Edge implements Comparable<Edge> {
17+
int v;
18+
int w;
19+
public Edge(int v, int w) {
20+
this.v = v;
21+
this.w = w;
22+
}
23+
@Override
24+
public int compareTo(Edge o) {
25+
return this.w - o.w;
26+
}
27+
}
28+
29+
public static void main(String[] args) throws IOException {
30+
br = new BufferedReader(new InputStreamReader(System.in));
31+
StringTokenizer st = new StringTokenizer(br.readLine());
32+
n = Integer.parseInt(st.nextToken());
33+
m = Integer.parseInt(st.nextToken());
34+
genders = new char[n + 1];
35+
st = new StringTokenizer(br.readLine());
36+
for (int i = 1; i <= n; i++) {
37+
genders[i] = st.nextToken().charAt(0);
38+
}
39+
graph = new ArrayList[n + 1];
40+
for (int i = 1; i <= n; i++) {
41+
graph[i] = new ArrayList<>();
42+
}
43+
for (int i = 0; i < m; i++) {
44+
st = new StringTokenizer(br.readLine());
45+
int u = Integer.parseInt(st.nextToken());
46+
int v = Integer.parseInt(st.nextToken());
47+
int w = Integer.parseInt(st.nextToken());
48+
//같은 성별 노드는 연결하지 않음
49+
if (genders[u] == genders[v]) continue;
50+
graph[u].add(new Edge(v, w));
51+
graph[v].add(new Edge(u, w));
52+
}
53+
54+
int answer = prim();
55+
System.out.println(answer);
56+
}
57+
58+
private static int prim() {
59+
boolean[] visited = new boolean[n + 1];
60+
PriorityQueue<Edge> pq = new PriorityQueue<>();
61+
int total = 0;
62+
int count = 0;
63+
visited[1] = true;
64+
count++;
65+
for (Edge e : graph[1]) {
66+
pq.add(e);
67+
}
68+
69+
while (!pq.isEmpty()) {
70+
Edge cur = pq.poll();
71+
if (visited[cur.v]) continue;
72+
visited[cur.v] = true;
73+
total += cur.w;
74+
count++;
75+
for (Edge next : graph[cur.v]) {
76+
if (!visited[next.v]) {
77+
pq.add(next);
78+
}
79+
}
80+
}
81+
82+
if (count == n) {
83+
return total;
84+
} else {
85+
return -1;
86+
}
87+
}
88+
}
89+
90+
```

0 commit comments

Comments
 (0)