From 51b9a84f5e5ac20ec9d84fc9145cf3fdfb2ec229 Mon Sep 17 00:00:00 2001 From: SinnoLn Date: Wed, 25 Nov 2026 23:05:54 +0900 Subject: [PATCH] 1319. Number of Operations to Make Network Connected --- ...Operations to Make Network Connected.java" | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 "leetcode3/\354\235\264\354\247\204\355\235\254/1319. Number of Operations to Make Network Connected.java" diff --git "a/leetcode3/\354\235\264\354\247\204\355\235\254/1319. Number of Operations to Make Network Connected.java" "b/leetcode3/\354\235\264\354\247\204\355\235\254/1319. Number of Operations to Make Network Connected.java" new file mode 100644 index 00000000..dfd60c8b --- /dev/null +++ "b/leetcode3/\354\235\264\354\247\204\355\235\254/1319. Number of Operations to Make Network Connected.java" @@ -0,0 +1,55 @@ +/* + +1. 아이디어 : 신장트리 구하기. 각 연결시 가중치가 없으므로 union-find로 신장트리를 구할 수 있는지 체크한다. + 1. untion(a,b)로 연결됐는지 확인후 연결됐다면 카운트 + 2. 모든 connections 배열을 체크했을 때 cnt==(n-1) 이면 전부 연결됐으므로 0 리턴 + 3. cnt가 (n-1)보다 작다면 n-1-cnt만큼의 선을 옮겨야함. 그러니 답은 (n-1-cnt) + 4. connections 배열 크기가 n-1보다 작다면 아예 신장트리를 만들 수 없으므로 미리 체크한다 + +2. 시간복잡도 : O(N + MA(N)) (A(N)은 거의 상수) + +3. 자료구조/알고리즘 : 신장트리 + union-find + + */ +class Solution { + int[] parent; + public int makeConnected(int n, int[][] connections) { + + if(connections.length < (n-1)) return -1; + + parent = new int[n]; + Arrays.fill(parent, -1); + int cnt = 0; + + for(int i=0; iparent[rootB]) parent[rootA] = rootB; + else if(parent[rootA]