結果

問題 No.3113 The farthest point
ユーザー tufusa
提出日時 2025-04-19 17:46:32
言語 Ruby
(3.4.1)
結果
TLE  
実行時間 -
コード長 1,190 bytes
コンパイル時間 643 ms
コンパイル使用メモリ 8,232 KB
実行使用メモリ 69,796 KB
最終ジャッジ日時 2025-04-19 17:46:40
合計ジャッジ時間 7,177 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample -- * 3
other TLE * 1 -- * 32
権限があれば一括ダウンロードができます
コンパイルメッセージ
Main.rb:36: warning: assigned but unused variable - ini
Syntax OK

ソースコード

diff #

class UnionFind
  def initialize(x)
    @par = Array(0...x)
    @rank = Array.new(x, 0)
  end

  def root(x)
    return x if @par[x] == x

    @par[x] = root(@par[x])
  end

  def unite(x, y)
    rx = root(x)
    ry = root(y)
    return if rx == ry

    case @rank[rx] <=> @rank[ry]
    when -1
      @par[rx] = ry
    when 1
      @par[ry] = rx
    when 0
      @par[rx] = ry
      @rank[ry] += 1
    end
  end

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

n = gets.to_i
g = Array.new(n) { [] }
ini = nil
uf = UnionFind.new n
posit = Array.new(n, false)
(n - 1).times do
  u, v, w = gets.split.map(&:to_i)
  u -= 1
  v -= 1

  g[u] << [v, w]
  g[v] << [u, w]
  uf.unite u, v if w >= 0
  posit[u] = posit[v] = true if w >= 0
end

def dfs(g, seen, now, cost)
  max = [now, cost]
  g[now].each do |nxt, w|
    next if seen[nxt]

    seen[nxt] = true
    res = dfs(g, seen, nxt, cost + w)
    max = res if max[1] < res[1]
  end

  max
end

max = 0
n.times do |i|
  next if uf.root(i) != i || !posit[i]

  seen = Array.new(n, false).tap { _1[i] = true }
  far1 = dfs(g, seen, i, 0)[0]

  seen.fill(false).tap { _1[far1] = true }
  max = [max, dfs(g, seen, far1, 0)[1]].max
end

puts max
0