Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] 집합의 표현 #214

Closed
hwangJi-dev opened this issue Apr 26, 2023 · 0 comments
Closed

[Algorithm] 집합의 표현 #214

hwangJi-dev opened this issue Apr 26, 2023 · 0 comments
Assignees
Labels

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Apr 26, 2023

💬 문제

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


💬 Idea

  • union-find를 이용하여 문제를 풀이했다. (공통 조상 찾기와 유사)

💬 풀이

import Foundation

func solution1717() {
    let nm = readLine()!.components(separatedBy: .whitespaces).map({ Int($0)! })
    var parent = [Int](0...nm[0])
    
    func find(_ b: Int) -> Int {
        if b != parent[b] {
            parent[b] = find(parent[b])
        }
        return parent[b]
    }
    
    func union(_ a: Int, _ b: Int) {
        let a = find(a)
        let b = find(b)
        
        if a >= b {
            parent[a] = b
        } else {
            parent[b] = a
        }
    }
    
    for _ in 1...nm[1] {
        let cal = readLine()!.components(separatedBy: .whitespaces).map({ Int($0)! })
        let a = cal[1]
        let b = cal[2]
        
        if cal[0] == 0 {
            union(a, b)
        } else {
            if find(a) == find(b) {
                print("YES")
            } else {
                print("NO")
            }
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant