結果

問題 No.860 買い物
ユーザー simansiman
提出日時 2022-04-26 04:56:51
言語 Ruby
(3.3.0)
結果
AC  
実行時間 560 ms / 1,000 ms
コード長 1,016 bytes
コンパイル時間 433 ms
コンパイル使用メモリ 11,504 KB
実行使用メモリ 36,748 KB
最終ジャッジ日時 2023-09-10 08:56:49
合計ジャッジ時間 8,119 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 78 ms
15,140 KB
testcase_01 AC 78 ms
15,036 KB
testcase_02 AC 78 ms
15,336 KB
testcase_03 AC 78 ms
15,128 KB
testcase_04 AC 78 ms
15,348 KB
testcase_05 AC 78 ms
15,140 KB
testcase_06 AC 94 ms
15,776 KB
testcase_07 AC 538 ms
36,548 KB
testcase_08 AC 541 ms
36,656 KB
testcase_09 AC 551 ms
36,748 KB
testcase_10 AC 549 ms
36,460 KB
testcase_11 AC 475 ms
35,240 KB
testcase_12 AC 477 ms
35,420 KB
testcase_13 AC 537 ms
36,484 KB
testcase_14 AC 560 ms
36,632 KB
testcase_15 AC 478 ms
35,404 KB
testcase_16 AC 553 ms
36,068 KB
testcase_17 AC 488 ms
35,144 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Main.rb:52: warning: assigned but unused variable - d
Main.rb:56: warning: assigned but unused variable - nc
Syntax OK

ソースコード

diff #

class UnionFind
  def initialize(n)
    @size = Array.new(n, 1)
    @rank = Array.new(n, 0)
    @parent = []

    (0..n).each do |i|
      @parent[i] = i
    end
  end

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

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

    if @rank[x] < @rank[y]
      @parent[x] = y
      @size[y] += @size[x]
    else
      @parent[y] = x
      @size[x] += @size[y]

      @rank[x] += 1 if @rank[x] == @rank[y]
    end
  end

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

  def size(x)
    @size[find(x)]
  end
end

N = gets.to_i

goods = N.times.map { gets.split.map(&:to_i) }
E = []
S = N

N.times do |i|
  c, d = goods[i]
  E << [i, N, c]

  if i + 1 < N
    nc, nd = goods[i + 1]
    E << [i, i + 1, nd]
  end
end

E.sort_by! { |_, _, cost| cost }
uf = UnionFind.new(N + 2)
ans = goods.map(&:first).sum

E.each do |u, v, cost|
  next if uf.same?(u, v)

  uf.unite(u, v)
  ans += cost
end

puts ans
0