Skip to content

Commit 587ea93

Browse files
authored
Merge pull request #1164 from AlgorithmWithGod/zinnnn37
[20251019] BOJ / P3 / 교수님은 기다리지 않는다 / 김민진
2 parents 746ca62 + 8ded16e commit 587ea93

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
```java
2+
import java.io.*;
3+
import java.util.StringTokenizer;
4+
5+
public class BJ_3830_교수님은_기다리지_않는다 {
6+
7+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
8+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
9+
private static final StringBuilder sb = new StringBuilder();
10+
private static StringTokenizer st;
11+
12+
private static int N, M;
13+
private static int[] parent, weight;
14+
15+
public static void main(String[] args) throws IOException {
16+
while (init()) {
17+
sol();
18+
}
19+
bw.flush();
20+
bw.close();
21+
br.close();
22+
}
23+
24+
private static boolean init() throws IOException {
25+
st = new StringTokenizer(br.readLine());
26+
N = Integer.parseInt(st.nextToken());
27+
M = Integer.parseInt(st.nextToken());
28+
29+
if (N == 0) return false;
30+
31+
parent = new int[N + 1];
32+
weight = new int[N + 1];
33+
for (int i = 1; i <= N; i++) {
34+
parent[i] = i;
35+
}
36+
37+
return true;
38+
}
39+
40+
private static void sol() throws IOException {
41+
while (M-- > 0) {
42+
st = new StringTokenizer(br.readLine());
43+
44+
String cmd = st.nextToken();
45+
46+
if (cmd.equals("!")) {
47+
int a = Integer.parseInt(st.nextToken());
48+
int b = Integer.parseInt(st.nextToken());
49+
int w = Integer.parseInt(st.nextToken());
50+
51+
union(a, b, w);
52+
} else if (cmd.equals("?")) {
53+
int a = Integer.parseInt(st.nextToken());
54+
int b = Integer.parseInt(st.nextToken());
55+
56+
if (find(a) == find(b)) {
57+
bw.write(weight[b] - weight[a] + "\n");
58+
} else {
59+
bw.write("UNKNOWN\n");
60+
}
61+
}
62+
}
63+
}
64+
65+
private static int find(int a) {
66+
if (a == parent[a]) return a;
67+
68+
int root = find(parent[a]);
69+
weight[a] += weight[parent[a]];
70+
parent[a] = root;
71+
72+
return root;
73+
}
74+
75+
private static void union(int a, int b, int w) {
76+
int rootA = find(a);
77+
int rootB = find(b);
78+
79+
if (rootA == rootB) {
80+
return;
81+
}
82+
83+
if (rootA < rootB) {
84+
parent[rootB] = rootA;
85+
weight[rootB] = weight[a] - weight[b] + w;
86+
} else {
87+
parent[rootA] = rootB;
88+
weight[rootA] = weight[b] - weight[a] - w;
89+
}
90+
}
91+
92+
}
93+
```

0 commit comments

Comments
 (0)