結果

問題 No.517 壊れたアクセサリー
ユーザー 👑 obakyanobakyan
提出日時 2022-02-18 00:02:51
言語 Lua
(LuaJit 2.1.1696795921)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,500 bytes
コンパイル時間 80 ms
コンパイル使用メモリ 5,216 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-11 17:57:24
合計ジャッジ時間 1,884 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 1 ms
4,380 KB
testcase_05 AC 1 ms
4,380 KB
testcase_06 AC 1 ms
4,380 KB
testcase_07 AC 1 ms
4,380 KB
testcase_08 AC 1 ms
4,376 KB
testcase_09 AC 1 ms
4,376 KB
testcase_10 AC 1 ms
4,380 KB
testcase_11 AC 1 ms
4,380 KB
testcase_12 AC 2 ms
4,376 KB
testcase_13 AC 1 ms
4,376 KB
testcase_14 AC 1 ms
4,376 KB
testcase_15 AC 1 ms
4,376 KB
testcase_16 AC 1 ms
4,380 KB
testcase_17 AC 1 ms
4,376 KB
testcase_18 AC 1 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

local n = io.read("*n", "*l")
local t = {}
for i = 1, 26 do t[i] = 0 end
local s1 = {}
for i = 1, n do
  local s = io.read()
  s1[i] = s
  for j = 1, #s do
    local v = s:byte(j) - 64
    t[v] = t[v] + 1
  end
end
local m = io.read("*n", "*l")
for i = 1, m do
  local s = io.read()
  s1[i + n] = s
  for j = 1, #s do
    local v = s:byte(j) - 64
    t[v] = t[v] + 1
  end
end
local w = {}
for i = 1, 26 do
  if t[i] == 1 then print(-1) os.exit() end
  if t[i] == 2 then
    table.insert(w, i)
    t[i] = #w
  end
end
local parent = {}
local left, right = {}, {}
for i = 1, #w do
  parent[i] = i
  left[i], right[i] = false, false
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, n + m do
  local si = s1[i]
  for j = 1, #si - 1 do
    local z1, z2 = t[si:byte(j) - 64], t[si:byte(j + 1) - 64]
    local r1, r2 = uf_findroot(z1), uf_findroot(z2)
    if r1 ~= r2 then
      parent[r2], parent[z2] = r1, r1
    end
    if right[z1] and right[z1] ~= z2 then
      print(-1) os.exit()
    end
    if left[z2] and left[z2] ~= z1 then
      print(-1) os.exit()
    end
    left[z2] = z1
    right[z1] = z2
  end
end
local r = uf_findroot(1)
for i = 2, #w do
  if r ~= uf_findroot(i) then
    print(-1) os.exit()
  end
end
while r do
  io.write(string.char(64 + w[r]))
  r = right[r]
end
io.write("\n")
0