From 5737de5c2b1b4554ae550b57c3043ec2e060b22a Mon Sep 17 00:00:00 2001 From: songyc macbook Date: Mon, 17 Nov 2025 20:36:22 +0900 Subject: [PATCH] 20251117 baekjoon --- code_study/Baekjoon/swift/20040.swift | 54 +++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 code_study/Baekjoon/swift/20040.swift diff --git a/code_study/Baekjoon/swift/20040.swift b/code_study/Baekjoon/swift/20040.swift new file mode 100644 index 0000000..c084f8e --- /dev/null +++ b/code_study/Baekjoon/swift/20040.swift @@ -0,0 +1,54 @@ +struct Union_Find { + var root: [Int] + + init(_ N: Int) { + self.root = Array(0...N) + } + + mutating func find(_ x: Int) -> Int { + if x == root[x] { + return x + } + + root[x] = find(root[x]) + return root[x] + } + + mutating func union(_ a: Int, _ b: Int) { + let x = find(a) + let y = find(b) + + if x>=y { + root[x] = y + } + else { + root[y] = x + } + } + + mutating func same_root(_ x: Int, _ y: Int) -> Bool { + return find(x) == find(y) + } +} + +if let input = readLine(), + let nums = input.split(separator: " ").compactMap({Int($0)}) as? [Int], + let N = nums.first, let M = nums.last +{ + var uf = Union_Find(N) + + var result = 0 + for m in 1...M { + guard let line = readLine(), + let point = line.split(separator: " ").map({Int($0)}) as? [Int], + let a = point.first, let b = point.last else { break } + + if uf.same_root(a, b) { + result = m + break + } + uf.union(a, b) + } + + print(result) +}