20251117 baekjoon

This commit is contained in:
songyc macbook 2025-11-17 20:36:22 +09:00
parent 26d486d52b
commit 5737de5c2b

View File

@ -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)
}