結果

問題 No.1059 素敵な集合
ユーザー 👑 obakyanobakyan
提出日時 2020-05-22 22:23:31
言語 Lua
(LuaJit 2.1.1734355927)
結果
AC  
実行時間 963 ms / 2,000 ms
コード長 2,607 bytes
コンパイル時間 211 ms
コンパイル使用メモリ 6,812 KB
実行使用メモリ 11,636 KB
最終ジャッジ日時 2024-07-23 09:31:01
合計ジャッジ時間 8,682 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 19
権限があれば一括ダウンロードができます

ソースコード

diff #

local mce, mfl, msq, mmi, mma, mab = math.ceil, math.floor, math.sqrt, math.min, math.max, math.abs

local function getprimes(x)
  local primes = {}
  local allnums = {}
  for i = 1, x do allnums[i] = true end
  for i = 2, x do
    if allnums[i] then
      table.insert(primes, i)
      local lim = mfl(x / i)
      for j = 2, lim do
        allnums[j * i] = false
      end
    end
  end
  return primes
end

local function getdivisorparts(x, primes)
  local prime_num = #primes
  local tmp = {}
  local lim = mce(msq(x))
  local primepos = 1
  local dv = primes[primepos]
  while primepos <= prime_num and dv <= lim do
    if x % dv == 0 then
      local t = {}
      t.p = dv
      t.cnt = 1
      x = mfl(x / dv)
      while x % dv == 0 do
        x = mfl(x / dv)
        t.cnt = t.cnt + 1
      end
      table.insert(tmp, t)
      lim = mce(msq(x))
    end
    if primepos == prime_num then break end
    primepos = primepos + 1
    dv = primes[primepos]
  end
  if x ~= 1 then
    local t = {}
    t.p, t.cnt = x, 1
    table.insert(tmp, t)
  end
  return tmp
end

local function getdivisorCore(divisorparts)
  local t = {}
  local pat = 1
  local len = #divisorparts
  local allpat = 1
  for i = 1, len do
    allpat = allpat * (1 + divisorparts[i].cnt)
  end
  for t_i_pat = 0, allpat - 1 do
    local div = allpat
    local i_pat = t_i_pat
    local ret = 1
    for i = 1, len do
      div = mfl(div / (divisorparts[i].cnt + 1))
      local mul = mfl(i_pat / div)
      i_pat = i_pat % div
      for j = 1, mul do
        ret = ret * divisorparts[i].p
      end
    end
    table.insert(t, ret)
  end
  table.sort(t)
  return t
end

local function getdivisor(x, primes)
  local dvp = getdivisorparts(x, primes)
  return getdivisorCore(dvp)
end

local l, r = io.read("*n", "*n")
-- local l, r = 5000, 200000
local primes = getprimes(r)
local parent = {}
for i = l, r do
  parent[i] = 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 = r, l, -1 do
  local dv = getdivisor(i, primes)
  local j = 1
  for k = 1, #dv do
    if l <= dv[k] then j = k break end
  end
  local dv1 = dv[j]
  local dv1p = uf_findroot(dv1)
  for k = j + 1, #dv do
    local dv2 = dv[k]
    local dv2p = uf_findroot(dv2)
    parent[dv2], parent[dv2p] = dv1p, dv1p
  end
end
local pmap, cnt = {}, 0
for i = l, r do
  local r = uf_findroot(i)
  if not pmap[r] then
    pmap[r] = true
    cnt = cnt + 1
  end
end
print(cnt - 1)
0