💬 문제
https://www.acmicpc.net/problem/1717
💬 Idea
- union-find를 이용하여 문제를 풀이했다. (공통 조상 찾기와 유사)
💬 풀이
import Foundation
func solution1717(){letnm=readLine()!.components(separatedBy:.whitespaces).map({Int($0)! })varparent=[Int](0...nm[0])func find(_ b:Int)->Int{if b !=parent[b]{parent[b]=find(parent[b])}returnparent[b]}func union(_ a:Int, _ b:Int){leta=find(a)letb=find(b)if a >= b {parent[a]= b
}else{parent[b]= a
}}for_in1...nm[1]{letcal=readLine()!.components(separatedBy:.whitespaces).map({Int($0)! })leta=cal[1]letb=cal[2]ifcal[0]==0{union(a, b)}else{iffind(a)==find(b){print("YES")}else{print("NO")}}}}
💬 문제https://www.acmicpc.net/problem/1717
💬 Idea💬 풀이