結果

問題 No.2290 UnUnion Find
ユーザー 👑 obakyanobakyan
提出日時 2023-05-05 23:46:31
言語 Lua
(LuaJit 2.1.1696795921)
結果
TLE  
実行時間 -
コード長 1,091 bytes
コンパイル時間 364 ms
コンパイル使用メモリ 5,120 KB
実行使用メモリ 10,624 KB
最終ジャッジ日時 2024-05-02 19:02:29
合計ジャッジ時間 5,000 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
10,624 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 131 ms
5,376 KB
testcase_03 TLE -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
testcase_30 -- -
testcase_31 -- -
testcase_32 -- -
testcase_33 -- -
testcase_34 -- -
testcase_35 -- -
testcase_36 -- -
testcase_37 -- -
testcase_38 -- -
testcase_39 -- -
testcase_40 -- -
testcase_41 -- -
testcase_42 -- -
testcase_43 -- -
testcase_44 -- -
testcase_45 -- -
testcase_46 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

local UF = {}
UF.create = function(self, n)
  self.parent = {}
  self.g = {}
  for i = 1, n do
    self.parent[i] = i
    self.g[i] = true
  end
end
UF.getroot = function(self, idx)
  local parent = self.parent
  local idx_update = idx
  while parent[idx] ~= idx do
    idx = parent[idx]
  end
  while parent[idx_update] ~= idx do
    parent[idx_update], idx_update = idx, parent[idx_update]
  end
  return idx
end
UF.unite = function(self, a, b)
  local ra = self:getroot(a)
  local rb = self:getroot(b)
  self.g[rb] = nil
  self.parent[b], self.parent[rb] = ra, ra
end
UF.new = function(n)
  local obj = {}
  setmetatable(obj, {__index = UF})
  obj:create(n)
  return obj
end

local n = io.read("*n")
local uf = UF.new(n)
local q = io.read("*n")
for iq = 1, q do
  local tp = io.read("*n")
  if tp == 1 then
    local a, b = io.read("*n", "*n")
    uf:unite(a, b)
  else
    local a = io.read("*n")
    local g = uf.g
    local k1, v1 = next(g)
    local k2, v2 = next(g, k1)
    if k2 then
      local r = uf:getroot(a)
      print(k1 + k2 - r)
    else
      print(-1)
    end
  end
end
0