結果

問題 No.1094 木登り / Climbing tree
ユーザー TANIGUCHI KousukeTANIGUCHI Kousuke
提出日時 2021-03-10 09:06:33
言語 Ruby
(3.3.0)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 1,910 bytes
コンパイル時間 101 ms
コンパイル使用メモリ 7,552 KB
実行使用メモリ 77,824 KB
最終ジャッジ日時 2024-04-20 05:31:25
合計ジャッジ時間 16,678 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 97 ms
12,416 KB
testcase_01 TLE -
testcase_02 AC 922 ms
57,984 KB
testcase_03 AC 663 ms
15,488 KB
testcase_04 AC 835 ms
40,704 KB
testcase_05 AC 1,395 ms
60,800 KB
testcase_06 AC 1,436 ms
33,024 KB
testcase_07 TLE -
testcase_08 TLE -
testcase_09 TLE -
testcase_10 TLE -
testcase_11 TLE -
testcase_12 TLE -
testcase_13 TLE -
testcase_14 TLE -
testcase_15 AC 1,403 ms
26,624 KB
testcase_16 TLE -
testcase_17 AC 1,665 ms
43,264 KB
testcase_18 AC 1,555 ms
35,072 KB
testcase_19 AC 1,813 ms
50,432 KB
testcase_20 TLE -
testcase_21 AC 1,664 ms
43,264 KB
testcase_22 TLE -
testcase_23 TLE -
testcase_24 TLE -
testcase_25 TLE -
testcase_26 TLE -
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

class LCA
  class << self
    def create(g, s = 0)
      parent = Array.new(g.size)
      active = Array.new(g.size, 0)
      depth = Array.new(g.size)
      tour = []
      
      u = parent[s] = s
      depth[s] = 0
      tour << s
      
      while true
        if (j = active[u]) >= g[u].size
          break if u == s
          u = parent[u]
          tour << u
          active[u] += 1
        else
          v, d = g[u][j]
          if !parent[v]
            parent[v] = u
            depth[v] = depth[u] + d
            u = v
            tour << u
          else
            active[u] += 1
          end
        end
      end
      new(tour, depth)
    end
  end

  def initialize(tour, depth)
    @tour = tour
    @depth = depth

    @ord = Array.new(depth.size)
    @offset = 1 << @tour.size.bit_length
    @data = Array.new(@offset << 1, -1)

    build!
  end

  def dist(a,b)
    c = lca(a,b)
    @depth[a] + @depth[b] - 2 * @depth[c]
  end

  def lca(a,b)
    a,b = b,a if @ord[b] < @ord[a]
    find_min(@ord[a], @ord[b] + 1)
  end
  private
  
  def find_min(a, b)
    x = -1
    l,r = @offset + a, @offset + b
    while l < r
      if l.odd?
        x = min_depth(x, @data[l]);
        l += l[0]
      end
      if r.odd?
        r -= r[0]; 
        x = min_depth(x, @data[r])
      end
      l >>= 1
      r >>= 1
    end
    return x
  end

  def min_depth(a,b)
    return b if a < 0
    return a if b < 0
    @depth[a] < @depth[b] ? a : b
  end

  def build!
    @tour.each_with_index do |u, i| 
      @data[@offset + i] = u
      @ord[u] = i if !@ord[u]
    end
    k = @offset
    @data[k] = min_depth(@data[2 * k], @data[2 * k + 1]) while (k -= 1) > 0
  end
  
end
N = gets.to_i
G = Array.new(N + 1){ [] }
(N - 1).times do
  u, v, d = gets.split.map(&:to_i)
  G[u] << [v, d]
  G[v] << [u, d]
end

lca = LCA.create(G, 1)

Q = gets.to_i
puts Q.times.map{ lca.dist(*gets.split.map(&:to_i)) }
0