From fd43912acab263cd251f151582465fef30e4a5bf Mon Sep 17 00:00:00 2001 From: suyeun84 <81475092+suyeun84@users.noreply.github.com> Date: Wed, 18 Jun 2025 23:04:08 +0900 Subject: [PATCH] =?UTF-8?q?[20250618]=20BOJ=20/=20G3=20/=20=EB=82=98?= =?UTF-8?q?=EB=A7=8C=20=EC=95=88=EB=90=98=EB=8A=94=20=EC=97=B0=EC=95=A0=20?= =?UTF-8?q?/=20=EA=B9=80=EC=88=98=EC=97=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...0\353\212\224 \354\227\260\354\225\240.md" | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 "suyeun84/202506/18 BOJ G3 \353\202\230\353\247\214 \354\225\210\353\220\230\353\212\224 \354\227\260\354\225\240.md" diff --git "a/suyeun84/202506/18 BOJ G3 \353\202\230\353\247\214 \354\225\210\353\220\230\353\212\224 \354\227\260\354\225\240.md" "b/suyeun84/202506/18 BOJ G3 \353\202\230\353\247\214 \354\225\210\353\220\230\353\212\224 \354\227\260\354\225\240.md" new file mode 100644 index 00000000..cace99be --- /dev/null +++ "b/suyeun84/202506/18 BOJ G3 \353\202\230\353\247\214 \354\225\210\353\220\230\353\212\224 \354\227\260\354\225\240.md" @@ -0,0 +1,70 @@ +```java +import java.io.*; +import java.util.*; + +public class boj14621 { + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + static StringTokenizer st; + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} + static int nextInt() {return Integer.parseInt(st.nextToken());} + + static int N, M, answer; + static char[] gender; + static Road[] roads; + static int[] parent; + public static void main(String[] args) throws Exception { + nextLine(); + N = nextInt(); + M = nextInt(); + answer = 0; + nextLine(); + gender = new char[N+1]; + roads = new Road[M]; + parent = new int[N+1]; + for (int i = 1; i <= N; i++) { + gender[i] = st.nextToken().charAt(0); + parent[i] = i; + } + for (int i = 0; i < M; i++) { + nextLine(); + int u = nextInt(); + int v = nextInt(); + int d = nextInt(); + roads[i] = new Road(u, v, d); + } + Arrays.sort(roads, (o1, o2) -> o1.d-o2.d); + int cnt = 0; + for (int i = 0; i < M; i++) { + if (gender[roads[i].s] == gender[roads[i].e]) continue; + if (find(roads[i].s) == find(roads[i].e)) continue; + answer += roads[i].d; + union(roads[i].s, roads[i].e); + cnt++; + } + if (cnt != N-1) System.out.println(-1); + else System.out.println(answer); + } + + static int find(int x) { + if (x == parent[x]) return x; + return parent[x] = find(parent[x]); + } + + static void union(int x, int y) { + x = parent[x]; + y = parent[y]; + + if (x