結果

問題 No.1293 2種類の道路
ユーザー semisagisemisagi
提出日時 2020-11-20 21:59:02
言語 Swift
(5.10.0)
結果
TLE  
実行時間 -
コード長 1,911 bytes
コンパイル時間 2,487 ms
コンパイル使用メモリ 133,724 KB
実行使用メモリ 8,068 KB
最終ジャッジ日時 2023-09-30 19:13:59
合計ジャッジ時間 7,777 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
8,068 KB
testcase_01 AC 3 ms
7,988 KB
testcase_02 AC 3 ms
8,008 KB
testcase_03 AC 4 ms
8,048 KB
testcase_04 AC 3 ms
8,000 KB
testcase_05 AC 4 ms
8,044 KB
testcase_06 AC 3 ms
7,944 KB
testcase_07 AC 3 ms
7,880 KB
testcase_08 AC 3 ms
8,012 KB
testcase_09 TLE -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

struct Scanner {
    private var elements = [String]()
    private var index = 0

    mutating func peek() -> String {
        while elements.count == index {
            elements = readLine()!.split(separator: " ").map(String.init)
            index = 0
        }
        return elements[index]
    }

    mutating func next() -> String {
        defer { index += 1 }
        return peek()
    }

    mutating func nextInt() -> Int {
        return Int(next())!
    }

    mutating func nextInts(_ n: Int) -> [Int] {
        return (0 ..< n).map { _ in nextInt() }
    }

    mutating func nextDouble() -> Double {
        return Double(next())!
    }
}

struct UnionFind {
    var parent: [Int]
    var count: [Int]

    init(_ n: Int) {
        parent = Array(0 ..< n)
        count = [Int](repeating: 1, count: n)
    }

    mutating func find(_ v: Int) -> Int {
        if v == parent[v] {
            return v
        }
        parent[v] = find(parent[v])
        return parent[v]
    }

    mutating func union(_ u: Int, _ v: Int) {
        var u = find(u)
        var v = find(v)
        guard u != v else { return }
        if count[u] < count[v] {
            swap(&u, &v)
        }
        count[u] += count[v]
        parent[v] = u
    }

    mutating func count(_ u: Int) -> Int {
        count[find(u)]
    }
}

var scanner = Scanner()

let N = scanner.nextInt()
let D = scanner.nextInt()
let W = scanner.nextInt()

var d = UnionFind(N)
var w = UnionFind(N)

for _ in 0 ..< D {
    let a = scanner.nextInt() - 1
    let b = scanner.nextInt() - 1
    d.union(a, b)
}

for _ in 0 ..< W {
    let c = scanner.nextInt() - 1
    let d = scanner.nextInt() - 1
    w.union(c, d)
}

var set = [Set<Int>](repeating: [], count: N)

for i in 0 ..< N {
    set[d.find(i)].insert(w.find(i))
}

var answer = 0
for i in 0 ..< N {
    answer += set[d.find(i)].map { w.count($0) }.reduce(0, +)
}
print(answer - N)
0