본문 바로가기

백준

[백준] 4195 친구 네트워크 [자바]

 


https://brenden.tistory.com/33

 

[알고리즘] 유니온 파인드 (Union-Find)

유니온 파인드(Union-Find) ① 유니온 파인드란? ▷ 대표적 그래프 알고리즘으로 '합집합 찾기'라는 의미를 가지고 있습니다. ▷ 상호 배타적 집합(Disjoint-set)이라고도 합니다. ▷ 여러 노드가 존재

brenden.tistory.com

https://steady-coding.tistory.com/111

 

[BOJ] 백준 4195번 : 친구 네트워크 (JAVA)

문제 민혁이는 소셜 네트워크 사이트에서 친구를 만드는 것을 좋아하는 친구이다. 우표를 모으는 취미가 있듯이, 민혁이는 소셜 네트워크 사이트에서 친구를 모으는 것이 취미이다. 어떤 사이

steady-coding.tistory.com

 

 


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {
	static int[] parent;
	static int[] level;
 	public static void main(String arg[]) throws IOException {
 		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 		StringBuilder sb = new StringBuilder();
 		int T = Integer.parseInt(br.readLine());
 		while(T --> 0) {
 			int count = 0;
 			HashMap<String, Integer> hashmap = new HashMap<>();
 			int M = Integer.parseInt(br.readLine());
 			parent = new int[M*2];
 			level = new int[M*2];
 			for(int i = 0; i < M*2; i++) {
 				parent[i] = i;
 				level[i] = 1;
 			}
 			for(int i = 0; i < M; i++) {
 				StringTokenizer st = new StringTokenizer(br.readLine(), " ");
 				String str1 = st.nextToken();
 				String str2 = st.nextToken();
 				int x = 0;
 				int y = 0;
 				if(!hashmap.containsKey(str1)) {
 					hashmap.put(str1, count++);
 				}
 				x = hashmap.get(str1);
 				if(!hashmap.containsKey(str2)) {
 					hashmap.put(str2, count++);
 				}
 				y = hashmap.get(str2);
 				union(x, y);
 				int cnt = 0;
 				cnt = find(x);
 				cnt = level[cnt];
 				sb.append(cnt).append('\n');
 			}
 		}
 		System.out.println(sb);
 	}
 	static int find(int x) {
 		if(x == parent[x]) {
 			return x;
 		}
 		return parent[x] = find(parent[x]);
 	}
 	static void union(int x, int y) {
 		x = find(x);
 		y = find(y);
 		if(x != y) {
 			if(x < y) {
 				parent[y] = x;
 				level[x] = level[y] + level[x];
 			}
 			else {
 				parent[x] = y;
 				level[y] = level[x] + level[y];
 			}
 		}
 	}
 	static boolean isSameParent(int x, int y) {
 		if(parent[x] == parent[y]) {
 			return true;
 		}
 		return false;
 	}
}

'백준' 카테고리의 다른 글

[백준] 1074 Z [자바]  (0) 2022.03.17
[백준] 1707 이분 그래프 [자바]  (0) 2022.03.17
[백준] 1033 칵테일 [자바]  (0) 2022.03.03
[백준] 9742 순열 [자바]  (0) 2022.03.02
[백준] 10827 a^b [자바]  (0) 2022.02.09