Skip to content

Commit 17427e3

Browse files
authored
[20250614] BOJ / P3 / 교수님은 기다리지 않는다 / 권혁준
1 parent 8d05ac7 commit 17427e3

File tree

1 file changed

+116
-0
lines changed

1 file changed

+116
-0
lines changed
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
class IOController {
6+
BufferedReader br;
7+
BufferedWriter bw;
8+
StringTokenizer st;
9+
10+
public IOController() {
11+
br = new BufferedReader(new InputStreamReader(System.in));
12+
bw = new BufferedWriter(new OutputStreamWriter(System.out));
13+
st = new StringTokenizer("");
14+
}
15+
16+
String nextLine() throws Exception {
17+
String line = br.readLine();
18+
st = new StringTokenizer(line);
19+
return line;
20+
}
21+
22+
String nextToken() throws Exception {
23+
while (!st.hasMoreTokens()) nextLine();
24+
return st.nextToken();
25+
}
26+
27+
int nextInt() throws Exception {
28+
return Integer.parseInt(nextToken());
29+
}
30+
31+
long nextLong() throws Exception {
32+
return Long.parseLong(nextToken());
33+
}
34+
35+
double nextDouble() throws Exception {
36+
return Double.parseDouble(nextToken());
37+
}
38+
39+
void close() throws Exception {
40+
bw.flush();
41+
bw.close();
42+
}
43+
44+
void write(String content) throws Exception {
45+
bw.write(content);
46+
}
47+
48+
}
49+
50+
public class Main {
51+
52+
static IOController io;
53+
54+
//
55+
56+
static int N, M;
57+
static int[] r;
58+
static long[] c;
59+
60+
public static void main(String[] args) throws Exception {
61+
62+
io = new IOController();
63+
64+
while(true) {
65+
N = io.nextInt();
66+
M = io.nextInt();
67+
if(N == 0) break;
68+
init();
69+
solve();
70+
}
71+
72+
io.close();
73+
74+
}
75+
76+
static int f(int x) {
77+
if(x == r[x]) return x;
78+
int p = f(r[x]);
79+
c[x] += c[r[x]];
80+
return (r[x] = p);
81+
}
82+
83+
public static void init() throws Exception {
84+
85+
r = new int[N+1];
86+
for(int i=1;i<=N;i++) r[i] = i;
87+
c = new long[N+1];
88+
89+
}
90+
91+
static void solve() throws Exception {
92+
93+
while(M-->0) {
94+
95+
char op = io.nextToken().charAt(0);
96+
int a = io.nextInt(), b = io.nextInt();
97+
98+
if(op == '!') {
99+
int w = io.nextInt();
100+
int x = f(a), y = f(b);
101+
if(x == y) continue;
102+
c[y] = c[a]-c[b]+w;
103+
r[y] = x;
104+
}
105+
else {
106+
int x = f(a), y = f(b);
107+
if(x != y) io.write("UNKNOWN\n");
108+
else io.write((c[b] - c[a]) + "\n");
109+
}
110+
111+
}
112+
113+
}
114+
115+
}
116+
```

0 commit comments

Comments
 (0)