Submission #3013010


Source Code Expand

class UnionFind
  attr_reader :rank, :parent, :value
  attr_writer :rank, :parent

  def initialize(x)
    @value = x
    @rank = 0
    @parent = self
  end

  def ==(obj)
    @value == obj.value
  end

  def find
    return self if self.parent == self
    root = self.parent.find
    self.parent = root
    root
  end

  def union(y)
    xr = find; yr = y.find
    return if xr == yr
    if xr.rank >= yr.rank
      yr.parent = xr
      xr.rank += 1
    else
      y.union(self)
    end
  end
end

def minimum_spanning_tree_kruskal(nodes, edges)
  # edges: [[node_from, node_to, weight]]
  edges.sort_by!{ |e| e[2] }
  th = Hash[nodes.map{ |x| [x, UnionFind.new(x)] }]
  i = 0
  mst = []
  while i < edges.size
    e = edges[i]
    i += 1
    f,t,w = *e
    tf = th[f]; tt = th[t]
    next if (tf.find == tt.find)
    tf.union(tt)
    mst << e
  end
  mst
end

N = gets.to_i
ns = (0...N).map{ |i| x,y = gets.split.map(&:to_i); { i: i, x: x, y: y } }
es = {}

[ :x, :y ].each{ |s|
  ns.sort_by!{ |n| n[s] }
  (1...N).each{ |i| 
    f,t = ns[i-1][:i],ns[i][:i]
    es[f] ||= {}
    es[f][t] = [ns[i][:x] - ns[i-1][:x], ns[i][:y] - ns[i-1][:y]].map(&:abs).min
  }
}

p minimum_spanning_tree_kruskal((0...N).to_a, es.map{ |f,e| e.map{ |t,w| [f,t,w] } }.flatten(1)).map{ |e| e[2] }.inject(:+)

Submission Info

Submission Time
Task D - Built?
User Corvvs
Language Ruby (2.3.3)
Score 500
Code Size 1352 Byte
Status AC
Exec Time 1643 ms
Memory 102012 KB

Compile Error

./Main.rb:43: warning: assigned but unused variable - w

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 1628 ms 102012 KB
02.txt AC 1602 ms 101852 KB
03.txt AC 1601 ms 101852 KB
04.txt AC 1615 ms 101852 KB
05.txt AC 1637 ms 101852 KB
06.txt AC 1591 ms 101852 KB
07.txt AC 1606 ms 101852 KB
08.txt AC 1643 ms 101852 KB
09.txt AC 1628 ms 101852 KB
10.txt AC 1601 ms 101852 KB
11.txt AC 1604 ms 101884 KB
12.txt AC 1593 ms 101852 KB
13.txt AC 1187 ms 92720 KB
14.txt AC 1197 ms 92720 KB
15.txt AC 1193 ms 92720 KB
16.txt AC 1443 ms 101904 KB
17.txt AC 1451 ms 101832 KB
18.txt AC 1193 ms 92720 KB
19.txt AC 1195 ms 92720 KB
20.txt AC 1419 ms 96244 KB
21.txt AC 1221 ms 92720 KB
22.txt AC 1315 ms 93284 KB
23.txt AC 995 ms 92732 KB
24.txt AC 1513 ms 101880 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