結果

問題 No.1843 Tree ANDistance
ユーザー maguroflymagurofly
提出日時 2022-02-18 21:34:59
言語 Ruby
(3.3.0)
結果
TLE  
実行時間 -
コード長 1,376 bytes
コンパイル時間 436 ms
コンパイル使用メモリ 11,460 KB
実行使用メモリ 87,548 KB
最終ジャッジ日時 2023-09-11 18:41:06
合計ジャッジ時間 44,938 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 TLE -
testcase_01 TLE -
testcase_02 TLE -
testcase_03 TLE -
testcase_04 TLE -
testcase_05 TLE -
testcase_06 TLE -
testcase_07 TLE -
testcase_08 TLE -
testcase_09 TLE -
testcase_10 TLE -
testcase_11 TLE -
testcase_12 TLE -
testcase_13 TLE -
testcase_14 AC 145 ms
17,820 KB
testcase_15 AC 149 ms
17,884 KB
testcase_16 AC 109 ms
16,584 KB
testcase_17 AC 106 ms
16,312 KB
testcase_18 AC 92 ms
15,712 KB
testcase_19 AC 163 ms
18,328 KB
testcase_20 AC 117 ms
16,524 KB
testcase_21 AC 78 ms
15,228 KB
testcase_22 AC 78 ms
15,160 KB
testcase_23 AC 77 ms
15,300 KB
testcase_24 AC 78 ms
15,136 KB
testcase_25 AC 78 ms
15,248 KB
testcase_26 AC 78 ms
15,180 KB
testcase_27 AC 79 ms
15,084 KB
testcase_28 AC 1,452 ms
82,208 KB
testcase_29 AC 983 ms
60,640 KB
testcase_30 AC 988 ms
59,208 KB
testcase_31 AC 1,566 ms
83,148 KB
testcase_32 AC 1,469 ms
80,984 KB
testcase_33 AC 522 ms
40,608 KB
testcase_34 AC 1,173 ms
69,704 KB
testcase_35 AC 78 ms
15,224 KB
testcase_36 AC 79 ms
15,052 KB
testcase_37 AC 79 ms
15,264 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

main = -> {
    N = gets.to_i
    edges = Array.new(N - 1) { a, b, c = gets.split.map(&:to_i); [a - 1, b - 1, c] }
    
    fact = Factorial.new(N, MOD)
    comb = (0 .. N).map { |c| fact.comb(c, 2) }
    
    ans = 0
    (0 .. 30).each do |bit|
        uf = UnionFind.new(N)
        edges.each do |a, b, c|
            uf.merge(a, b) if c[bit] == 1
        end
        leaders = (0 ... N).map { uf.leader(_1) }.uniq
        ans += leaders.sum { |i| comb[uf.size(i)] } * 2.pow(bit, MOD)
        ans %= MOD
    end
    
    puts ans
}

MOD = 10**9 + 7

class Factorial
  def initialize(max, mod)
    @mod = mod
    @fac = [1, 1]
    @fin = [1, 1]
    @inv = [nil, 1]
    (2 .. max).each do |i|
      @fac[i] = @fac[i - 1] * i % mod
      @inv[i] = mod - @inv[mod % i] * (mod / i) % mod
      @fin[i] = @fin[i - 1] * @inv[i] % mod
    end
  end
  
  def fact(n)
    @fac[n]
  end
  
  def comb(n, k)
    return 0 if n < k or n < 0 or k < 0
    @fac[n] * @fin[k] % @mod * @fin[n - k] % @mod
  end
end

class UnionFind
  def initialize(size); @p = Array.new(size, -1); end
  def leader(i); j = i; j, i = i, @p[j] = @p[i] until @p[i] < 0; i; end
  def merge(i, j); k, l = leader(i), leader(j); return false if k == l; k, l = l, k if @p[k] > @p[l]; @p[k] += @p[l]; @p[l] = k; true; end
  def same?(i, j); leader(i) == leader(j); end
  def size(i); -@p[leader(i)]; end
end

main.call
0