結果

問題 No.1843 Tree ANDistance
ユーザー maguroflymagurofly
提出日時 2022-02-18 21:33:56
言語 Ruby
(3.3.0)
結果
TLE  
実行時間 -
コード長 1,336 bytes
コンパイル時間 402 ms
コンパイル使用メモリ 11,344 KB
実行使用メモリ 82,872 KB
最終ジャッジ日時 2023-09-11 18:39:11
合計ジャッジ時間 17,171 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
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 151 ms
17,692 KB
testcase_15 AC 157 ms
18,100 KB
testcase_16 AC 113 ms
16,404 KB
testcase_17 AC 109 ms
16,272 KB
testcase_18 AC 95 ms
15,792 KB
testcase_19 AC 169 ms
18,692 KB
testcase_20 AC 121 ms
16,704 KB
testcase_21 AC 83 ms
15,208 KB
testcase_22 AC 82 ms
15,144 KB
testcase_23 AC 83 ms
15,244 KB
testcase_24 AC 81 ms
15,296 KB
testcase_25 AC 80 ms
15,292 KB
testcase_26 AC 81 ms
15,220 KB
testcase_27 AC 80 ms
15,264 KB
testcase_28 AC 1,507 ms
81,732 KB
testcase_29 AC 1,021 ms
59,260 KB
testcase_30 AC 1,040 ms
61,248 KB
testcase_31 AC 1,631 ms
82,872 KB
testcase_32 AC 1,545 ms
80,568 KB
testcase_33 AC 543 ms
40,364 KB
testcase_34 AC 1,244 ms
67,304 KB
testcase_35 AC 81 ms
15,300 KB
testcase_36 AC 79 ms
15,076 KB
testcase_37 AC 81 ms
15,312 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)
    
    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| fact.comb(uf.size(i), 2) } * 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