Submission #17562463
Source Code Expand
struct UnionFind { var par:[Int] var rank:[Int] var n:Int //最初は全てが根であるとして初期化 init(n:Int){ self.n = n self.par = Array(repeating:0,count:n) self.rank = Array(repeating:0,count:n) for i in 0..<n{ par[i] = i } } // データxが属する木の根を再帰で得る:root(x) = {xの木の根} mutating func root(x:Int) -> Int { if par[x] == x{ return x } else{ return root(x:par[x]) } } // xとyの木を併合 mutating func unite (x:Int,y:Int){ let x = root(x:x) let y = root(x:y) if x == y{ return } if rank[x] < rank[y]{ par[x] = y } else { par[y] = x if rank[x] == rank[y]{ rank[x] += 1 } } } // 2つのデータx, yが属する木が同じならtrueを返す mutating func same(x:Int,y:Int)->Bool{ return root(x:x) == root(x:y) } } // 標準入力の受け取り let input = readLine()!.split(separator:" ").map{Int($0)!} let n = input[0] let m = input[1] // UnionFindの初期化 var check = UnionFind(n:n) // 連結させる for _ in 0..<m{ let ab = readLine()!.split(separator:" ").map{Int($0)!} let a = ab[0]-1 let b = ab[1]-1 check.unite(x:a,y:b) } // 根の数をカウント (答えは (根の数) - 1) var ans = -1 for i in 0..<n{ if i == check.root(x:i){ ans += 1 } } // 答えの出力 print(ans)
Submission Info
Submission Time | |
---|---|
Task | B - 道路工事 |
User | tardigrade |
Language | Swift (5.2.1) |
Score | 100 |
Code Size | 1654 Byte |
Status | AC |
Exec Time | 277 ms |
Memory | 9840 KiB |
Judge Result
Set Name | Sample | All | ||||
---|---|---|---|---|---|---|
Score / Max Score | 0 / 0 | 100 / 100 | ||||
Status |
|
|
Set Name | Test Cases |
---|---|
Sample | sample1.txt, sample2.txt |
All | 0.txt, 1.txt, 10.txt, 11.txt, 12.txt, 13.txt, 14.txt, 15.txt, 16.txt, 17.txt, 18.txt, 19.txt, 2.txt, 3.txt, 4.txt, 5.txt, 6.txt, 7.txt, 8.txt, 9.txt, sample1.txt, sample2.txt |
Case Name | Status | Exec Time | Memory |
---|---|---|---|
0.txt | AC | 14 ms | 8004 KiB |
1.txt | AC | 8 ms | 8276 KiB |
10.txt | AC | 5 ms | 8256 KiB |
11.txt | AC | 5 ms | 7988 KiB |
12.txt | AC | 5 ms | 7944 KiB |
13.txt | AC | 5 ms | 8004 KiB |
14.txt | AC | 5 ms | 8300 KiB |
15.txt | AC | 202 ms | 8300 KiB |
16.txt | AC | 10 ms | 9840 KiB |
17.txt | AC | 6 ms | 9372 KiB |
18.txt | AC | 6 ms | 9560 KiB |
19.txt | AC | 277 ms | 9712 KiB |
2.txt | AC | 8 ms | 7988 KiB |
3.txt | AC | 5 ms | 7940 KiB |
4.txt | AC | 5 ms | 8144 KiB |
5.txt | AC | 11 ms | 7924 KiB |
6.txt | AC | 5 ms | 8140 KiB |
7.txt | AC | 6 ms | 8028 KiB |
8.txt | AC | 4 ms | 8024 KiB |
9.txt | AC | 6 ms | 8036 KiB |
sample1.txt | AC | 8 ms | 8260 KiB |
sample2.txt | AC | 5 ms | 8256 KiB |