Skip to content

Commit fd43912

Browse files
authored
[20250618] BOJ / G3 / 나만 안되는 연애 / 김수연
1 parent 3685c17 commit fd43912

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class boj14621 {
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, answer;
12+
static char[] gender;
13+
static Road[] roads;
14+
static int[] parent;
15+
public static void main(String[] args) throws Exception {
16+
nextLine();
17+
N = nextInt();
18+
M = nextInt();
19+
answer = 0;
20+
nextLine();
21+
gender = new char[N+1];
22+
roads = new Road[M];
23+
parent = new int[N+1];
24+
for (int i = 1; i <= N; i++) {
25+
gender[i] = st.nextToken().charAt(0);
26+
parent[i] = i;
27+
}
28+
for (int i = 0; i < M; i++) {
29+
nextLine();
30+
int u = nextInt();
31+
int v = nextInt();
32+
int d = nextInt();
33+
roads[i] = new Road(u, v, d);
34+
}
35+
Arrays.sort(roads, (o1, o2) -> o1.d-o2.d);
36+
int cnt = 0;
37+
for (int i = 0; i < M; i++) {
38+
if (gender[roads[i].s] == gender[roads[i].e]) continue;
39+
if (find(roads[i].s) == find(roads[i].e)) continue;
40+
answer += roads[i].d;
41+
union(roads[i].s, roads[i].e);
42+
cnt++;
43+
}
44+
if (cnt != N-1) System.out.println(-1);
45+
else System.out.println(answer);
46+
}
47+
48+
static int find(int x) {
49+
if (x == parent[x]) return x;
50+
return parent[x] = find(parent[x]);
51+
}
52+
53+
static void union(int x, int y) {
54+
x = parent[x];
55+
y = parent[y];
56+
57+
if (x<y) parent[y] = x;
58+
else parent[x] = y;
59+
}
60+
61+
static class Road {
62+
int s, e, d;
63+
public Road(int s, int e, int d) {
64+
this.s = s;
65+
this.e = e;
66+
this.d = d;
67+
}
68+
}
69+
}
70+
```

0 commit comments

Comments
 (0)