結果

問題 No.2382 Amidakuji M
ユーザー 👑 obakyan
提出日時 2023-07-16 00:49:51
言語 Lua
(LuaJit 2.1.1734355927)
結果
AC  
実行時間 78 ms / 2,000 ms
コード長 1,179 bytes
コンパイル時間 159 ms
コンパイル使用メモリ 7,072 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-09-17 09:12:00
合計ジャッジ時間 1,962 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 19
権限があれば一括ダウンロードができます

ソースコード

diff #

local band = bit.band
local FenwickTree = {}
FenwickTree.create = function(self, n)
  self.n = n
  self.v = {}
  for i = 1, n do self.v[i] = 0 end
end
FenwickTree.add = function(self, pos, val)
  while pos <= self.n do
    self.v[pos] = self.v[pos] + val
    pos = pos + band(pos, -pos)
  end
end
FenwickTree.sum = function(self, r)
  local ret = 0
  while 0 < r do
    ret = ret + self.v[r]
    r = r - band(r, -r)
  end
  return ret
end
FenwickTree.new = function(n)
  local obj = {}
  setmetatable(obj, {__index = FenwickTree})
  obj:create(n)
  return obj
end

local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
long long atoll(const char*);
]]

local function lltonumber(str)
  return C.atoll(str)
end

local n, m = io.read():match("(%d+) (%d+)")
n = tonumber(n)
m = lltonumber(m)
local v = 0
local fw = FenwickTree.new(n)
for i = 1, n do
  local p = io.read("*n")
  v = v + i - 1 - fw:sum(p)
  fw:add(p, 1)
end
local a = 0LL
while a < 1LL * v do
  a = a + m
end
if (a - 1LL * v) % 2LL == 0LL then
  local ans = tostring(a):gsub("LL", "")
  print(ans)
else
  if v % 2 == 1 then
    print(-1)
  else
    local ans = tostring(a + m):gsub("LL", "")
    print(ans)
  end
end
0