結果

問題 No.556 仁義なきサルたち
ユーザー letrangerjpletrangerjp
提出日時 2017-10-31 18:47:29
言語 Ruby
(3.3.0)
結果
AC  
実行時間 118 ms / 2,000 ms
コード長 1,361 bytes
コンパイル時間 45 ms
コンパイル使用メモリ 7,424 KB
実行使用メモリ 12,544 KB
最終ジャッジ日時 2024-05-02 01:43:56
合計ジャッジ時間 3,144 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 99 ms
12,288 KB
testcase_01 AC 89 ms
12,160 KB
testcase_02 AC 90 ms
12,160 KB
testcase_03 AC 89 ms
12,288 KB
testcase_04 AC 88 ms
12,416 KB
testcase_05 AC 89 ms
12,288 KB
testcase_06 AC 90 ms
12,160 KB
testcase_07 AC 91 ms
12,160 KB
testcase_08 AC 90 ms
12,288 KB
testcase_09 AC 90 ms
12,288 KB
testcase_10 AC 94 ms
12,416 KB
testcase_11 AC 93 ms
12,544 KB
testcase_12 AC 104 ms
12,288 KB
testcase_13 AC 99 ms
12,544 KB
testcase_14 AC 102 ms
12,416 KB
testcase_15 AC 105 ms
12,288 KB
testcase_16 AC 105 ms
12,544 KB
testcase_17 AC 114 ms
12,416 KB
testcase_18 AC 118 ms
12,544 KB
testcase_19 AC 115 ms
12,288 KB
testcase_20 AC 118 ms
12,544 KB
testcase_21 AC 118 ms
12,544 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

# https://www.leighhalliday.com/weighted-quick-union-find-algorithm-in-ruby
class UnionFind

  attr_accessor :nodes, :sizes

  def initialize(num)
    self.nodes = []
    self.sizes = []

    num.times do |n|
      self.nodes[n] = n
      self.sizes[n] = 1
    end
  end

  def root(i)
    # Loop up the chain until reaching root
    while nodes[i] != i do
      # path compression for future lookups
      nodes[i] = nodes[nodes[i]]
      i = nodes[i]
    end
    i
  end

  def union(i, j)
    rooti = root i
    rootj = root j

    # already connected
    return if rooti == rootj

    # root smaller to root of larger
    if sizes[i] < sizes[j]
      nodes[rooti] = rootj
      sizes[rootj] += sizes[rooti]
    else
      nodes[rootj] = rooti
      sizes[rooti] += sizes[rootj]
    end
  end

  def connected?(i, j)
    root(i) == root(j)
  end

end

class Mafia < UnionFind
  def fight(i, j)
    rooti = root i
    rootj = root j

    return if rooti == rootj

    if sizes[rooti] < sizes[rootj] || sizes[rooti] == sizes[rootj] && rooti > rootj
      nodes[rooti] = rootj
      sizes[rootj] += sizes[rooti]
    else
      nodes[rootj] = rooti
      sizes[rooti] += sizes[rootj]
    end
  end
end

N, M = gets.split.map &:to_i
apes = Mafia.new(N+1)
$<.each{|s|
  a, b = s.split.map &:to_i
  apes.fight(a, b)
}
puts apes.nodes[1..-1].map{|i|
  apes.root i
}
0