[BOJ_1976] μ¬νκ°μ (골λ4) - JAVA
πΎ μκ³ λ¦¬μ¦
- Union - Find : μλ‘μ μ§ν©μ μ΄μ©ν΄μ νκΈ°!
- μ΄ μΈμλ bfs, νλ‘μ΄λ-μμ¬ μκ³ λ¦¬μ¦μ νμ©ν΄ νμ΄ κ°λ₯
πΎ μκ° ν¬μΈνΈ
- 6λ²μ λ λ©λͺ¨λ¦¬μ΄κ³Όμ λ°νμμλ¬κ° λ¬λλ°, μ€λ₯λ₯Ό μμ νλλΌ νμ°Έ κ³ λ―Όνλ€. μ€λ₯κ° λ κ³³μ λ€λ¦μλ union method, μ¬κΈ°μ find(x)λ₯Ό xλ‘ μ μνκ³ find(y)λ₯Ό yλ‘ μ¬μ μν κ²μ΄ λ¬Έμ μλ€. γ γ κ·Έ μμΈμ μ½κ² μ°Ύμ μ μμ΄ μ±μ§νΌν°μκ² λ¬Όμ΄λ³΄μλ€.
private static void union(int x, int y) {
// x = find(x);
// y = find(y);
//
// if (x > y)
// parent[x] = y;
// parent[y] = x;
μ§μ λΉκ΅νλ©΄ μλͺ»λ κ²°κ³Όκ° λμ¬ μ μλ€λ μ ,, μ΄λ μ λμ¨ νμΈλ μκ³ λ¦¬μ¦μ νν μ€μ μ€ νλλΌλ μ ,, λͺ μ¬ λ λͺ μ¬
κ²½λ‘ μμΆ(Path Compression)μ find ν¨μκ° νΈμΆλ λ ν΄λΉ λ ΈλλΆν° 루νΈκΉμ§μ κ²½λ‘ μμ λͺ¨λ λ Έλμ λΆλͺ¨λ₯Ό μ§μ 루νΈλ‘ λ§λ€μ΄μ£Όλ κΈ°μ μ λλ€. μ΄λ κ² νλ©΄ κ°μ μ§ν©μ μν λ Έλλ€μ΄ λ μ§§μ κ²½λ‘λ‘ λ£¨νΈμ λλ¬ν μ μκ² λμ΄, find ν¨μμ νΈμΆ μκ°μ μ€μΌ μ μμ΅λλ€.
κ·Έλ¬λ x = find(x);μ κ°μ΄ μ§μ xλ₯Ό 루νΈλ‘ λ§λ€λ©΄μ ν λΉνκ² λλ©΄, find ν¨μ λ΄λΆμμμ μ¬κ· νΈμΆμ΄ μ¬λΌμ§κ² λ©λλ€. μ¬κ· νΈμΆμ΄ μλ€λ κ²μ κ²½λ‘ μμΆμ μ μ©νμ§ μμλ€λ κ²μ΄λ©°, μ΄λ find ν¨μλ₯Ό μ¬λ¬ λ² νΈμΆν λλ§λ€ νμ 루νΈμ λλ¬νλ λ° λ λ§μ μκ°μ΄ μμλ μ μλ€λ κ²μ μλ―Έν©λλ€.
By Chat GPT
5
5
0 1 0 0 0
1 0 0 0 1
0 0 0 1 0
0 0 1 0 1
0 1 0 1 0
3 5 4 2 1
ν΄λΉ λ°λ‘μμ 무νμΌλ‘ λΉλΉ λλ©° μ€νμ€λ²νλ‘μ° νμ νμΈ
πΎ μμ€μ½λ
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main_1976 {
static int[] parent;
static int N, M;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
N = Integer.parseInt(br.readLine()); // λμμ μ
M = Integer.parseInt(br.readLine()); // μ¬νκ³νμ μν λμλ€μ μ
parent = new int[N + 1];
for (int i = 1; i < N + 1; i++) {
parent[i] = i;
}
for (int i = 1; i < N + 1; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 1; j < N + 1; j++) {
int num = Integer.parseInt(st.nextToken());
// λ λμκ° μ°κ²°λμ΄μμΌλ©΄, λΆλͺ¨λ₯Ό νλλ‘ ν΅μΌμν€μ! (μ λμ¨)
if (num == 1)
union(i, j);
}
}
// μ¬νκ³ν
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
for (int i = 1; i < M; i++) {
int now = Integer.parseInt(st.nextToken());
if (find(start) != find(now)) {
// μμμ κ³Ό κ·Έ νκ° μ΄μ΄μ Έμμ§ μμΌλ©΄ μ¬νλΆκ°λ₯
bw.write("NO\n");
bw.flush();
bw.close();
br.close();
return;
}
}
bw.write("YES\n");
bw.flush();
bw.close();
br.close();
}
// μ΅μμ λΆλͺ¨(λν)μ°ΎκΈ°
private static int find(int x) {
if (x != parent[x])
return parent[x] = find(parent[x]);
return x;
}
// λμ μ°κ²°νκΈ°
private static void union(int x, int y) {
// x = find(x);
// y = find(y);
//
// if (x > y)
// parent[x] = y;
// parent[y] = x;
int a = find(x);
int b = find(y);
if (a > b) {
parent[a] = b;
} else {
parent[b] = a;
}
}
}
π΅π« 곡λΆν΄μΌ ν μ
- μ λμ¨νμΈλ λ¨μ μκΈ°κ° μλ μ΄ν΄ν΄μ νκ²...
- μκΎΈ μκΈ°λ‘ μ΄μ΄μ§λ€... γ γ μ리λ₯Ό μ΄ν΄νμ