Skip to content

Commit d127d3e

Browse files
authored
[20260222] BOJ / G3 / 불우이웃돕기 / 이준희
1 parent 68e9948 commit d127d3e

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
7+
static int[] parent;
8+
9+
static class Edge implements Comparable<Edge> {
10+
int u, v, w;
11+
Edge(int u, int v, int w) {
12+
this.u = u;
13+
this.v = v;
14+
this.w = w;
15+
}
16+
@Override
17+
public int compareTo(Edge o) {
18+
return this.w - o.w;
19+
}
20+
}
21+
22+
public static void main(String[] args) throws IOException {
23+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
24+
StringTokenizer st;
25+
int N = Integer.parseInt(br.readLine());
26+
27+
List<Edge> edges = new ArrayList<>();
28+
long totalLength = 0;
29+
30+
for (int i = 0; i < N; i++) {
31+
String line = br.readLine();
32+
for (int j = 0; j < N; j++) {
33+
char c = line.charAt(j);
34+
int len = charToInt(c);
35+
36+
if (len > 0) {
37+
totalLength += len;
38+
if (i != j) {
39+
edges.add(new Edge(i, j, len));
40+
}
41+
}
42+
}
43+
}
44+
45+
Collections.sort(edges);
46+
47+
parent = new int[N];
48+
for (int i = 0; i < N; i++) parent[i] = i;
49+
50+
int useEdgeCount = 0;
51+
long mstSum = 0;
52+
53+
for (Edge edge : edges) {
54+
if (union(edge.u, edge.v)) {
55+
mstSum += edge.w;
56+
useEdgeCount++;
57+
}
58+
}
59+
60+
if (useEdgeCount == N - 1) {
61+
System.out.println(totalLength - mstSum);
62+
} else {
63+
System.out.println(-1);
64+
}
65+
}
66+
67+
static int charToInt(char c) {
68+
if (c >= 'a' && c <= 'z') return c - 'a' + 1;
69+
if (c >= 'A' && c <= 'Z') return c - 'A' + 27;
70+
return 0;
71+
}
72+
73+
static int find(int x) {
74+
if (parent[x] == x) return x;
75+
return parent[x] = find(parent[x]);
76+
}
77+
78+
static boolean union(int x, int y) {
79+
int rootX = find(x);
80+
int rootY = find(y);
81+
if (rootX != rootY) {
82+
parent[rootX] = rootY;
83+
return true;
84+
}
85+
return false;
86+
}
87+
}
88+
```

0 commit comments

Comments
 (0)