-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathHW_150366.java
More file actions
124 lines (105 loc) ยท 4.04 KB
/
HW_150366.java
File metadata and controls
124 lines (105 loc) ยท 4.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import java.util.*;
class HW_150366 {
static int n = 2500;
static int grp[];
static String values[];
public String[] solution(String[] commands) {
grp = new int[n];
values = new String[n];
List<String> answers = new ArrayList<>();
for(int i = 0; i < n; i++){
grp[i] = i;
}
StringTokenizer st;
for(int i = 0; i < commands.length; i++){
st = new StringTokenizer(commands[i]);
int r, c;
String v;
switch(st.nextToken()){
case "UPDATE" : // UPDATE ์ถ์ถ
String v1 = st.nextToken(); // v1 ์ถ์ถ
String v2 = st.nextToken(); // v2 ์ถ์ถ
if(st.hasMoreTokens()){ // ๋จ์์๋ ํ ํฐ์ด ์๋ ๊ฒฝ์ฐ (UPDATE v1 v2 value)
String value = st.nextToken(); // value ์ถ์ถ
r = Integer.parseInt(v1) - 1;
c = Integer.parseInt(v2) - 1;
values[find(r * 50 + c)] = value;
}
else{ // UPDATE v1 v2
for(int j = 0; j < n; j++){
if(values[find(j)] != null && values[find(j)].equals(v1)){
values[find(j)] = v2;
}
}
}
break;
case "MERGE" :
int r1 = Integer.parseInt(st.nextToken()) - 1;
int c1 = Integer.parseInt(st.nextToken()) - 1;
int r2 = Integer.parseInt(st.nextToken()) - 1;
int c2 = Integer.parseInt(st.nextToken()) - 1;
int num1 = r1*50 + c1;
int num2 = r2*50 + c2;
// ๊ฐ์ด ์๋ ํ์ด ๋ํ๊ฐ ๋์ง ์๊ฒ ์ฒ๋ฆฌ
if(values[find(num1)] == null && values[find(num2)] != null){
int temp = num1;
num1 = num2;
num2 = temp;
}
union(num1, num2); // ๋ ์นธ ๋ณํฉ
break;
case "UNMERGE" :
r = Integer.parseInt(st.nextToken()) - 1;
c = Integer.parseInt(st.nextToken()) - 1;
int g = find(r*50 +c); // ๋ํ ์นธ ์ฐพ๊ธฐ
v = values[g]; // ๋ํ ์นธ์ ๊ฐ์ ์ ์ฅ
// ๊ฒฝ๋ก ์์ถ
for(int j = 0; j < n; j++){
find(j);
}
for(int j = 0; j < n; j++){
if(find(j) == g){
grp[j] = j; // ๋์ผํ ๋ํ ์นธ์ ๊ฐ์ง ๊ฒฝ์ฐ ์ด๊ธฐํ
if(j == r*50 + c){
values[j] = v; // ์ง์ ๋ ์นธ์ ๊ฐ ์ ์ง
}else{
values[j] = null; // ๋๋จธ์ง ์นธ ์ด๊ธฐํ
}
}
}
break;
case "PRINT" :
r = Integer.parseInt(st.nextToken()) - 1;
c = Integer.parseInt(st.nextToken()) - 1;
v = values[find(r*50 + c)];
if(v == null){
answers.add("EMPTY");
}
else answers.add(v);
break;
}
}
String[] answer = new String[answers.size()];
for(int i = 0; i < answers.size(); i++){
answer[i] = answers.get(i);
}
return answer;
}
// ์์๊ฐ ์ํ ๊ทธ๋ฃน ์์๋ด๊ธฐ
static int find(int idx){
if(idx == grp[idx]){
return idx;
}
return grp[idx] = find(grp[idx]);
}
// ๊ทธ๋ฃน ํฉ์น๊ธฐ
static void union(int g1, int g2){
g1 = find(g1);
g2 = find(g2);
if(g1 == g2){
return;
}
values[g2] = null;
grp[g2] = g1;
}
}