結果

問題 No.1420 国勢調査 (Easy)
ユーザー 👑 obakyan
提出日時 2022-03-29 20:53:48
言語 Lua
(LuaJit 2.1.1734355927)
結果
AC  
実行時間 218 ms / 2,000 ms
コード長 1,286 bytes
コンパイル時間 253 ms
コンパイル使用メモリ 7,076 KB
実行使用メモリ 23,808 KB
最終ジャッジ日時 2024-11-08 19:21:27
合計ジャッジ時間 7,858 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 30
権限があれば一括ダウンロードができます

ソースコード

diff #

local bxor = bit.bxor

local n, m = io.read("*n", "*n")
local a, b, y = {}, {}, {}
local edge = {}
local parent = {}
for i = 1, n do
  parent[i] = i
  edge[i] = {}
end
local function uf_findroot(idx)
  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
for i = 1, m do
  a[i], b[i], y[i] = io.read("*n", "*n", "*n")
  local ra, rb = uf_findroot(a[i]), uf_findroot(b[i])
  parent[rb], parent[b[i]] = ra, ra
  table.insert(edge[a[i]], i)
  table.insert(edge[b[i]], i)
end
local ans = {}
local asked = {}
for i = 1, n do
  asked[i] = false
  ans[i] = 0
end
local tasks = {}
for i = 1, n do
  if uf_findroot(i) == i then
    asked[i] = true
    table.insert(tasks, i)
  end
end
local done = 0
while done < #tasks do
  done = done + 1
  local src = tasks[done]
  for i = 1, #edge[src] do
    local ei = edge[src][i]
    local dst = a[ei] == src and b[ei] or a[ei]
    local yi = y[ei]
    if asked[dst] then
      if bxor(ans[src], ans[dst]) ~= yi then
        print(-1) os.exit()
      end
    else
      asked[dst] = true
      ans[dst] = bxor(ans[src], yi)
      table.insert(tasks, dst)
    end
  end
end
print(table.concat(ans, "\n"))
0