20251004 baekjoon

This commit is contained in:
songyc macbook 2025-10-04 22:47:30 +09:00
parent 6d3192d0ae
commit c71fbad897

View File

@ -0,0 +1,77 @@
import java.util.Scanner;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.stream.IntStream;
class UnionFind {
private int [] data;
UnionFind(int N) {
this.data = IntStream.rangeClosed(0, N).toArray();
}
public int find(int x) {
if(this.data[x] != x) {
return this.data[x] = this.find(this.data[x]);
}
return this.data[x];
}
public void union(int a, int b) {
int rootA = this.find(a);
int rootB = this.find(b);
if(rootA != rootB) {
if(rootA < rootB) this.data[rootB] = rootA;
else this.data[rootA] = rootB;
}
}
public void setRoot(int index, int root) {
this.data[index] = root;
}
}
public class _1043 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
UnionFind uf = new UnionFind(N);
int M = sc.nextInt();
int truthNum = sc.nextInt();
int[] truthGroup = new int[truthNum];
for(int i=0; i<truthNum; i++) {
truthGroup[i] = sc.nextInt();
uf.setRoot(truthGroup[i], 0);
}
@SuppressWarnings("unchecked")
ArrayList<Integer>[] partyInfo = new ArrayList[M]; // 2중 ArrayList로 선언해도 되지만 제네릭 배열타입 연습을 위해 방법을 이용함.
for(int i=0; i<M; i++) {
partyInfo[i] = new ArrayList<>();
int personNum = sc.nextInt();
for(int j=0; j<personNum; j++) {
partyInfo[i].add(sc.nextInt());
}
}
sc.close();
for (ArrayList<Integer> party : partyInfo) {
for(int i=1; i<party.size(); i++) {
uf.union(party.get(0), party.get(i));
}
}
int canLie = 0;
for (ArrayList<Integer> party : partyInfo) {
if(uf.find(party.get(0)) != 0) canLie++;
}
System.out.println(canLie);
}
}