結果

問題 No.1170 Never Want to Walk
ユーザー semisagisemisagi
提出日時 2020-08-14 21:38:34
言語 Swift
(6.0.3)
結果
AC  
実行時間 353 ms / 2,000 ms
コード長 2,436 bytes
コンパイル時間 8,914 ms
コンパイル使用メモリ 130,840 KB
実行使用メモリ 22,664 KB
最終ジャッジ日時 2024-10-10 14:40:50
合計ジャッジ時間 15,375 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

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 {
        let value = peek()
        index += 1
        return value
    }

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

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

extension Array where Element == Int {
    func lowerBound(_ value: Int) -> Int {
        var l = -1
        var r = count
        while l + 2 <= r {
            let m = (l + r) / 2
            if self[m] >= value {
                r = m
            } else {
                l = m
            }
        }
        return r
    }

    func upperBound(_ value: Int) -> Int {
        return lowerBound(value + 1)
    }
}

var scanner = Scanner()

let N = scanner.nextInt()
let A = scanner.nextInt()
let B = scanner.nextInt()
let X = (0 ..< N).map { _ in scanner.nextInt() }

var unionfind = UnionFind(N)

var count = [Int](repeating: 0, count: N)

func connect(index i: Int, l: Int, r: Int) {
    if r - l == 1 {
        unionfind.union(i, l)
    } else if r - l >= 2 {
        unionfind.union(i, l)
        count[l] += 1
        count[r - 1] -= 1
    }
}

for i in X.indices {
    connect(index: i, l: X.lowerBound(X[i] - B), r: X.upperBound(X[i] - A))
    connect(index: i, l: X.lowerBound(X[i] + A), r: X.upperBound(X[i] + B))
}

for i in 0 ..< N - 1 {
    count[i + 1] += count[i]
    if count[i] > 0 {
        unionfind.union(i, i + 1)
    }
}

for i in 0 ..< N {
    print(unionfind.count(i))
}
0