Submission #2529643


Source Code Expand

class UnionFind
    def initialize(n)
        @par = Array.new(n)
        n.times{ |i| @par[i] = i }
        @rank = Array.new(n, 0)
    end

    def find(x)
        if @par[x] == x
            x
        else
            @par[x] = find(@par[x])
        end
    end

    def unite(x,y)
        x = find(x)
        y = find(y)
        return if x == y

        if @rank[x] < @rank[y]
            @par[x] = y
        else
            @par[y] = x
            @rank[x] += 1 if @rank[x] == @rank[y]
        end
    end

    def same?(x, y)
        find(x) == find(y)
    end
end

# edge = [src, dst, cost]
def kruskal(n, edges)
    edges = edges.sort_by{|edge| edge[2]}
    uf = UnionFind.new(n)
    res = 0
    edges.each do |edge|
        u = edge[0]
        v = edge[1]
        unless uf.same?(u, v)
            uf.unite(u, v)
            res += edge[2]
        end
    end
    return res
end


N = gets.to_i
xys = []
N.times do |i|
    xys[i] = [i] + gets.split.map(&:to_i)
end

xsort = xys.sort_by{|arr| arr[1]}
ysort = xys.sort_by{|arr| arr[2]}

edges = []
(N-1).times do |i|
    m, n = xsort[i][0], xsort[i+1][0]
    dist = [(xys[m][1]-xys[n][1]).abs, (xys[m][2]-xys[n][2]).abs].min
    edges.push([m, n, dist])
    m, n = ysort[i][0], ysort[i+1][0]
    dist = [(xys[m][1]-xys[n][1]).abs, (xys[m][2]-xys[n][2]).abs].min
    edges.push([m, n, dist])
end

puts kruskal(N, edges)

Submission Info

Submission Time
Task D - Built?
User betrue12
Language Ruby (2.3.3)
Score 500
Code Size 1446 Byte
Status AC
Exec Time 857 ms
Memory 33616 KB

Judge Result

Set Name Sample All
Score / Max Score 0 / 0 500 / 500
Status
AC × 2
AC × 28
Set Name Test Cases
Sample s1.txt, s2.txt
All 01.txt, 02.txt, 03.txt, 04.txt, 05.txt, 06.txt, 07.txt, 08.txt, 09.txt, 10.txt, 11.txt, 12.txt, 13.txt, 14.txt, 15.txt, 16.txt, 17.txt, 18.txt, 19.txt, 20.txt, 21.txt, 22.txt, 23.txt, 24.txt, 25.txt, 26.txt, s1.txt, s2.txt
Case Name Status Exec Time Memory
01.txt AC 845 ms 32976 KB
02.txt AC 838 ms 32976 KB
03.txt AC 842 ms 32976 KB
04.txt AC 845 ms 33616 KB
05.txt AC 845 ms 32976 KB
06.txt AC 841 ms 32976 KB
07.txt AC 842 ms 32976 KB
08.txt AC 854 ms 32976 KB
09.txt AC 857 ms 32976 KB
10.txt AC 841 ms 32976 KB
11.txt AC 855 ms 32976 KB
12.txt AC 838 ms 32976 KB
13.txt AC 709 ms 31440 KB
14.txt AC 703 ms 31312 KB
15.txt AC 753 ms 32592 KB
16.txt AC 753 ms 31952 KB
17.txt AC 764 ms 31952 KB
18.txt AC 745 ms 31440 KB
19.txt AC 783 ms 32208 KB
20.txt AC 788 ms 32976 KB
21.txt AC 795 ms 32592 KB
22.txt AC 798 ms 32464 KB
23.txt AC 666 ms 31324 KB
24.txt AC 801 ms 32976 KB
25.txt AC 7 ms 1788 KB
26.txt AC 7 ms 1788 KB
s1.txt AC 7 ms 1788 KB
s2.txt AC 7 ms 1788 KB