JosephCha의 개발일지

[백준] 4195번 / 친구 네트워크 (Swift) 본문

알고리즘 및 자료구조

[백준] 4195번 / 친구 네트워크 (Swift)

JosephCha 2022. 8. 23. 20:55
반응형

https://www.acmicpc.net/problem/4195

 

4195번: 친구 네트워크

첫째 줄에 테스트 케이스의 개수가 주어진다. 각 테스트 케이스의 첫째 줄에는 친구 관계의 수 F가 주어지며, 이 값은 100,000을 넘지 않는다. 다음 F개의 줄에는 친구 관계가 생긴 순서대로 주어진

www.acmicpc.net

  • Union-Find 알고리즘을 사용하여 풀어야 하는데, Union-Find 알고리즘은 원소들의 연결 여부를 확인하는 알고리즘이다.
  • Find 함수 : 파라미터의 루트 부모를 찾음 (재귀로 찾음)
  • Union 함수 : 오른쪽 파라미터의 루트 부모를 왼쪽의 루트 부모로 만듬 (즉 왼쪽 루트 부모가 제일 최강 루트 부모가 되는것)
  • 친구 관계가 생길때마다 네트워크 수는 Union함수가 호출될때마다, 왼쪽루트 부모의 네트워크 수 + 오른쪽 루트 부모의 네트워크 수
import Foundation

let testCase = Int(readLine()!)!

for _ in 0..<testCase {
    let relationShipCount = Int(readLine()!)!
    
        var parentDic = [String: String]()
        var count = [String: Int]()
        
        func find(_ x: String) -> String {
            if x == parentDic[x]! {
                return x
            } else {
                let routeParent = find(parentDic[x]!)
                parentDic[x] = routeParent
                return parentDic[x]!
            }
        }
        
        func union(_ x: String, _ y: String) {
            let parentX = find(x)
            let parentY = find(y)
            
            if parentX != parentY {
                parentDic[parentY] = parentX
                count[parentX]! += count[parentY]! // 왼쪽루트 부모의 네트워크 수 + 오른쪽 루트 부모의 네트워크 수
            }
        }
    for _ in 0..<relationShipCount {
        let names = readLine()!.split(separator: " ").map{String($0)}
        let left = names[0]
        let right = names[1]
        
        if parentDic.keys.contains(left) == false {
            parentDic[left] = left
            count[left] = 1
        }
        
        if parentDic.keys.contains(right) == false {
            parentDic[right] = right
            count[right] = 1
        }
        
        union(left, right)
        print(count[find(left)]!)
    }
}

'알고리즘 및 자료구조' 카테고리의 다른 글

[백준] 1543번 문제 / 문서 검색  (0) 2022.09.06
[스택] 백준/1874번/스택 수열  (0) 2022.07.27
[브루트 포스]백준/2798번/블랙잭  (0) 2022.07.26
백준/2920번/음계 문제  (0) 2022.07.26
  (0) 2022.04.20
Comments