--https://www.lua.org/pil/11.4.html
local List = {}
function List.new ()
  return {first = 0, last = -1}
end

function List.pushleft (list, value)
  local first = list.first - 1
  list.first = first
  list[first] = value
end

function List.pushright (list, value)
  local last = list.last + 1
  list.last = last
  list[last] = value
end

function List.popleft (list)
  local first = list.first
  if first > list.last then return false end
  local value = list[first]
  list[first] = nil
  list.first = first + 1
  return value
end

function List.popright (list)
  local last = list.last
  if list.first > last then return false end
  local value = list[last]
  list[last] = nil
  list.last = last - 1
  return value
end

----------

local h,w=io.read("n","n","l")
local a={}
for i=1,h do
    local input=io.read()
    a[i]={}
    for j=1,w do
        a[i][j]=input:byte(j)
    end
end

local dist={}
for i=1,h do
    for j=1,w do
        dist[i][j]=-1
    end
end

local iue=List.new()
local jue=List.new()
for i=1,h do
    dist[i]={}
    for j=1,w do
        if a[i][j]==35 then
            dist[i][j]=0
            List.pushright(iue,i)
            List.pushright(jue,j)
        end
    end
end

local di={1,0,-1,0}
local dj={0,1,0,-1}
while true do
    local i=List.popleft(iue)
    if not i then
        break
    end
    local j=List.popleft(jue)
    for k=1,4 do
        local ni=i+di[k]
        local nj=j+dj[k]
        if ni<1 or ni>h or nj<1 or nj>w then
        else
            if dist[ni][nj]==-1 then
                dist[ni][nj]=dist[i][j]+1
                List.pushright(iue,ni)
                List.pushright(jue,nj)
            end
        end
    end
end

local max=0
for i=1,h do
    for j=1,w do
        max=math.max(max,dist[i][j])
    end
end
print(max)


--https://www.lua.org/pil/11.4.html
local List = {}
function List.new ()
  return {first = 0, last = -1}
end

function List.pushleft (list, value)
  local first = list.first - 1
  list.first = first
  list[first] = value
end

function List.pushright (list, value)
  local last = list.last + 1
  list.last = last
  list[last] = value
end

function List.popleft (list)
  local first = list.first
  if first > list.last then return false end
  local value = list[first]
  list[first] = nil
  list.first = first + 1
  return value
end

function List.popright (list)
  local last = list.last
  if list.first > last then return false end
  local value = list[last]
  list[last] = nil
  list.last = last - 1
  return value
end

----------

local h,w=io.read("n","n","l")
local a={}
for i=1,h do
    local input=io.read()
    a[i]={}
    for j=1,w do
        a[i][j]=input:byte(j)
    end
end

local dist={}
local iue=List.new()
local jue=List.new()
for i=1,h do
    dist[i]={}
    for j=1,w do
        if a[i][j]==35 then
            dist[i][j]=0
            List.pushright(iue,i)
            List.pushright(jue,j)
        else
            dist[i][j]=-1
        end
    end
end

local di={1,0,-1,0}
local dj={0,1,0,-1}
while true do
    local i=List.popleft(iue)
    if not i then
        break
    end
    local j=List.popleft(jue)
    for k=1,4 do
        local ni=i+di[k]
        local nj=j+dj[k]
        if ni<1 or ni>h or nj<1 or nj>w then
            goto continue
        end
        if dist[ni][nj]==-1 then
            dist[ni][nj]=dist[i][j]+1
            List.pushright(iue,ni)
            List.pushright(jue,nj)
        end
        ::continue::
    end
end

local max=0
for i=1,h do
    for j=1,w do
        max=math.max(max,dist[i][j])
    end
end
print(max)

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 2

3

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


--https://www.lua.org/pil/11.4.html
local List = {}
function List.new ()
  return {first = 0, last = -1}
end

function List.pushleft (list, value)
  local first = list.first - 1
  list.first = first
  list[first] = value
end

function List.pushright (list, value)
  local last = list.last + 1
  list.last = last
  list[last] = value
end

function List.popleft (list)
  local first = list.first
  if first > list.last then return false end
  local value = list[first]
  list[first] = nil
  list.first = first + 1
  return value
end

function List.popright (list)
  local last = list.last
  if list.first > last then return false end
  local value = list[last]
  list[last] = nil
  list.last = last - 1
  return value
end

----------

local h,w=io.read("n","n","l")
local a={}
for i=1,h do
    local input=io.read()
    a[i]={}
    for j=1,w do
        a[i][j]=input:byte(j)
    end
end

local dist={}
local iue=List.new()
local jue=List.new()
for i=1,h do
    dist[i]={}
    for j=1,w do
        if a[i][j]==35 then
            dist[i][j]=0
            List.pushright(iue,i)
            List.pushright(jue,j)
        else
            dist[i][j]=-1
        end
    end
end

local di={1,0,-1,0}
local dj={0,1,0,-1}
while true do
    local i=List.popleft(iue)
    if not i then
        break
    end
    local j=List.popleft(jue)
    for k=1,4 do
        local ni=i+di[k]
        local nj=j+dj[k]
        if ni<1 or ni>h or nj<1 or nj>w then
        else
            if dist[ni][nj]==-1 then
                dist[ni][nj]=dist[i][j]+1
                List.pushright(iue,ni)
                List.pushright(jue,nj)
            end
        end
    end
end

local max=0
for i=1,h do
    for j=1,w do
        max=math.max(max,dist[i][j])
    end
end
print(max)


local h, w = io.read("*n", "*n", "*l")
local tasks = {}
local len = {}
for i = 1, h do
  s = io.read()
  for j = 1, w do
    local idx = (i - 1) * w + j
    if s:sub(j, j) == "#" then
      len[idx] = 0
      table.insert(tasks, idx)
    else
      len[idx] = 1000000007
    end
  end
end
local done = 0

local function walk(src, dst)
  if len[src] + 1 < len[dst] then
    len[dst] = len[src] + 1
    table.insert(tasks, dst)
  end
end

for i = 1, h * w do
  local idx = tasks[i]
  if w < idx then walk(idx, idx - w) end
  if idx <= (h - 1) * w then walk(idx, idx + w) end
  if 1 < w then
    if idx % w ~= 0 then walk(idx, idx + 1) end
    if idx % w ~= 1 then walk(idx, idx - 1) end
  end
end
local ans = len[1]
local mma = math.max
for i = 2, h * w do
  ans = mma(ans, len[i])
end
print(ans)


local h, w = io.read("*n", "*n", "*l")
local tasks = {}
local len = {}
for i = 1, h do
  s = io.read()
  for j = 1, w do
    local idx = (i - 1) * w + j
    if s:sub(j, j) == "#" then
      len[idx] = 0
      table.insert(tasks, idx)
    else
      len[idx] = 1000000007
    end
  end
end
local done = 0

local function walk(src, dst)
  if len[src] + 1 < len[dst] then
    len[dst] = len[src] + 1
    table.insert(tasks, dst)
  end
end

while done < #tasks do
  done = done + 1
  local idx = tasks[done]
  if w < idx then walk(idx, idx - w) end
  if idx <= (h - 1) * w then walk(idx, idx + w) end
  if 1 < w then
    if idx % w ~= 0 then walk(idx, idx + 1) end
    if idx % w ~= 1 then walk(idx, idx - 1) end
  end
end
local ans = len[1]
for i = 2, h * w do
  ans = math.max(ans, len[i])
end
print(ans)


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

------
local H, W = io.read("*n", "*n", "*l")
local grid = {}
local distance = {}
for i=1, H do
    grid[i] = str2tbl(io.read("*l"))
    distance[i] = {}
    local grid_i, distance_i = grid[i], distance[i]
    for j=1, W do
        distance_i[j] = grid_i[j] == '#' and 0 or 2001
    end
end
local math_min = math.min
for i=1, H do
    local distance_i = distance[i]
    for j=2, W do
        distance_i[j] = math_min(distance_i[j], distance_i[j-1] + 1)
    end
end
for i=1, H do
    local distance_i = distance[i]
    for j=W-1, 1, -1 do
        distance_i[j] = math_min(distance_i[j], distance_i[j+1] + 1)
    end
end
for i=2, H do
    local distance_i = distance[i]
    local distance_im1 = distance[i-1]
    for j=1, W do
        distance_i[j] = math_min(distance_i[j], distance_im1[j] + 1)
    end
end
for i=H-1, 1, -1 do
    local distance_i = distance[i]
    local distance_ip1 = distance[i+1]
    for j=1, W do
        distance_i[j] = math_min(distance_i[j], distance_ip1[j] + 1)
    end
end
local ans = 0
local math_max = math.max
for i=1, H do
    local distance_i = distance[i]
    for j=1, W do
        ans = math_max(ans, distance_i[j])
    end
end
print(ans)


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

-- http://www.lua.org/pil/11.4.html
local function List_new()
    local tbl = {}
    local first = 1
    local last = 0
    local function count()
        return last - first + 1
    end
    local function pushright(value)
        local new_last = last + 1
        last = new_last
        tbl[last] = value
    end
    local function popleft(value)
        --if first > last then error("list is empty") end
        local value = tbl[first]
        tbl[first] = nil
        first = first + 1
        return value
    end
    return {pushright, popleft, count}
end
local pushright, popleft, count = 1, 2, 3

------
local H, W = io.read("*n", "*n", "*l")
local grid = {}
for i=1, H do
    grid[i] = str2tbl(io.read("*l"))
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local ans = 0
local blacks = List_new()
local blacks_used = {}
for i=1, 1000*1000+1000 do
    blacks_used[i] = false
end
local function not_blacks_used(i, j)
    local k = i*1000+j
    local used = blacks_used[k]
    blacks_used[k] = true
    return not used
end
for i=1, H do
    for j=1, W do
        local c = grid[i][j]
        if c == '#' then
            if not_blacks_used(i, j) then
                blacks[pushright](i)
                blacks[pushright](j)
            end
        end
    end
end
local dx = {-1, 1, 0, 0}
local dy = {0, 0, -1, 1}

local next = List_new()
while blacks[count]() > 0 do
    while blacks[count]() > 0 do
        local i = blacks[popleft]()
        local j = blacks[popleft]()
        for k=1, 4 do
            local x, y = i + dx[k], j + dy[k]
            if x >= 1 and x <= H and y >= 1 and y <= W then
                if not_blacks_used(x, y) then
                    next[pushright](x)
                    next[pushright](y)
                end
            end
        end
    end
    ans = ans + 1
    blacks, next = next, blacks
end
print(ans-1)


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

-- http://www.lua.org/pil/11.4.html
List = {}
function List.new()
  return setmetatable({first = 0, last = -1}, {__index = List})
end

function List:pushleft(value)
  local first = self.first - 1
  self.first = first
  self[first] = value
end

function List:pushright(value)
  local last = self.last + 1
  self.last = last
  self[last] = value
end

function List:popleft()
  local first = self.first
  if first > self.last then error("list is empty") end
  local value = self[first]
  self[first] = nil        -- to allow garbage collection
  self.first = first + 1
  return value
end

function List:popright()
  local last = self.last
  if self.first > last then error("list is empty") end
  local value = self[last]
  self[last] = nil         -- to allow garbage collection
  self.last = last - 1
  return value
end

function List:count()
    return self.last - self.first + 1
end

------
local H, W = io.read("*n", "*n", "*l")
local grid = {}
for i=1, H do
    grid[i] = str2tbl(io.read("*l"))
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local count = 0
local blacks = List.new()
local blacks_used = {}
local function not_blacks_used(i, j)
    if not blacks_used[i*1000+j] then
        blacks_used[i*1000+j] = true
        return true
    end
    return false
end
for i=1, H do
    for j=1, W do
        local c = grid[i][j]
        if c == '#' then
            if not_blacks_used(i, j) then
                blacks:pushright({i, j})
            end
        end
    end
end
local tuples = {{-1,0},{1,0},{0,-1},{0,1}}
local next = List.new()
while blacks:count() > 0 do
    while blacks:count() > 0 do
        local t = blacks:popleft()
        local i, j = t[1], t[2]
        for _, tuple in ipairs(tuples) do
            local x,y = i + tuple[1], j + tuple[2]
            if x >= 1 and x <= H and y >= 1 and y <= W then
                if not_blacks_used(x, y) then
                    next:pushright({x, y})
                end
            end
        end
    end
    count = count + 1
    blacks, next = next, blacks
end
print(count-1)


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

-- http://www.lua.org/pil/11.4.html
List = {}
function List.new()
  return setmetatable({first = 0, last = -1}, {__index = List})
end

function List:pushleft(value)
  local first = self.first - 1
  self.first = first
  self[first] = value
end

function List:pushright(value)
  local last = self.last + 1
  self.last = last
  self[last] = value
end

function List:popleft()
  local first = self.first
  if first > self.last then error("list is empty") end
  local value = self[first]
  self[first] = nil        -- to allow garbage collection
  self.first = first + 1
  return value
end

function List:popright()
  local last = self.last
  if self.first > last then error("list is empty") end
  local value = self[last]
  self[last] = nil         -- to allow garbage collection
  self.last = last - 1
  return value
end

function List:count()
    return self.last - self.first + 1
end

do
    local a = List.new()
    assert(a:count() == 0)
    a:pushleft(1)
    assert(a:count() == 1)
    a:pushright(1)
    assert(a:count() == 2)
    a:popleft()
    assert(a:count() == 1)
    a:popright()
    assert(a:count() == 0)
    a = nil
end

------
local H, W = io.read("*n", "*n", "*l")
local grid = {}
for i=1, H do
    grid[i] = str2tbl(io.read("*l"))
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local count = 0
local blacks = List.new()
local blacks_used = {}
local function not_blacks_used(i, j)
    if not blacks_used[i*1000+j] then
        blacks_used[i*1000+j] = true
        return true
    end
    return false
end
for i=1, H do
    for j=1, W do
        local c = grid[i][j]
        if c == '#' then
            if not_blacks_used(i, j) then
                blacks:pushright({i, j})
            end
        end
    end
end
local tuples = {{-1,0},{1,0},{0,-1},{0,1}}
while blacks:count() > 0 do
    local next = List.new()
    while blacks:count() > 0 do
        local t = blacks:popleft()
        local i, j = t[1], t[2]
        for _, tuple in ipairs(tuples) do
            local x,y = i + tuple[1], j + tuple[2]
            if x >= 1 and x <= H and y >= 1 and y <= W then
                if not_blacks_used(x, y) then
                    next:pushright({x, y})
                end
            end
        end
    end
    count = count + 1
    blacks = next
end
print(count-1)


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

-- http://www.lua.org/pil/11.4.html
local function List_new()
    local tbl = {}
    local first = 1
    local last = 0
    local function count()
        return last - first + 1
    end
    local function pushright(value)
        local new_last = last + 1
        last = new_last
        tbl[last] = value
    end
    local function popleft(value)
        --if first > last then error("list is empty") end
        local value = tbl[first]
        tbl[first] = nil
        first = first + 1
        return value
    end
    return pushright, popleft, count
end

------
local H, W = io.read("*n", "*n", "*l")
local grid = {}
for i=1, H do
    grid[i] = str2tbl(io.read("*l"))
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local loops = 0
local count = 0
local blacks_pushright, blacks_popleft, blacks_count = List_new()
local blacks_used = {}
for i=1, 1000*1000 + 1000 do
    blacks_used[i] = false
end
local function not_blacks_used(i, j)
    if not blacks_used[i*1000+j] then
        blacks_used[i*1000+j] = true
        return true
    end
    return false
end
for i=1, H do
    for j=1, W do
        local c = grid[i][j]
        loops = loops + 1
        if c == '#' then
            if not_blacks_used(i, j) then
                blacks_pushright({i, j})
            end
        end
    end
end

local cur_count = 0
while blacks_count() > 0 do
    for bc=blacks_count(),1,-1 do
        local t = blacks_popleft()
        local i, j = t[1], t[2]
        for dyx=0,3 do
            local y01, x01 = dyx/2 - dyx/2%1, dyx%2
            local dy = y01 * (-1 + 2 * x01)
            local dx = (1 - y01) * (-1 + 2 * x01)
            --print(dyx,y01,x01,dy,dx)
            local x = i + dx
            local y = j + dy
            if x >= 1 and x <= H and y >= 1 and y <= W then
                if not_blacks_used(x, y) then
                    blacks_pushright({x, y})
                end
            end
        end
    end
    count = count + 1
end
print(count-1)


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

-- http://www.lua.org/pil/11.4.html
List = {}
function List.new()
  return setmetatable({first = 0, last = -1}, {__index = List})
end

function List:pushleft(value)
  local first = self.first - 1
  self.first = first
  self[first] = value
end

function List:pushright(value)
  local last = self.last + 1
  self.last = last
  self[last] = value
end

function List:popleft()
  local first = self.first
  if first > self.last then error("list is empty") end
  local value = self[first]
  self[first] = nil        -- to allow garbage collection
  self.first = first + 1
  return value
end

function List:popright()
  local last = self.last
  if self.first > last then error("list is empty") end
  local value = self[last]
  self[last] = nil         -- to allow garbage collection
  self.last = last - 1
  return value
end

function List:count()
    return self.last - self.first + 1
end

do
    local a = List.new()
    assert(a:count() == 0)
    a:pushleft(1)
    assert(a:count() == 1)
    a:pushright(1)
    assert(a:count() == 2)
    a:popleft()
    assert(a:count() == 1)
    a:popright()
    assert(a:count() == 0)
    a = nil
end

------
local H, W = io.read("*n", "*n", "*l")
local grid = {}
for i=1, H do
    grid[i] = str2tbl(io.read("*l"))
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local count = 0
local blacks = List.new()
local blacks_used = {}
local function not_blacks_used(i, j)
    if not blacks_used[i*1000+j] then
        blacks_used[i*1000+j] = true
        return true
    end
    return false
end
for i=1, H do
    for j=1, W do
        local c = grid[i][j]
        if c == '#' then
            if not_blacks_used(i, j) then
                blacks:pushright({i, j})
            end
        end
    end
end
while blacks:count() > 0 do
    local next = List.new()
    while blacks:count() > 0 do
        local t = blacks:popleft()
        local i, j = t[1], t[2]
        local tuples = {{i-1,j},{i+1,j},{i,j-1},{i,j+1}}
        for _, tuple in ipairs(tuples) do
            local x,y = tuple[1], tuple[2]
            if x >= 1 and x <= H and y >= 1 and y <= W then
                if not_blacks_used(x, y) then
                    next:pushright({x, y})
                end
            end
        end
    end
    count = count + 1
    blacks = next
end
print(count-1)


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

------
local H, W = io.read("*n", "*n", "*l")
local grid = {}
local distance = {}
for i=1, H do
    grid[i] = str2tbl(io.read("*l"))
    distance[i] = {}
    for j=1, W do
        distance[i][j] = 2001
    end
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local blacks = {}
for i=1, H do
    for j=1, W do
        local c = grid[i][j]
        if c == '#' then
            table.insert(blacks, {i, j})
        end
    end
end
for _, t in ipairs(blacks) do
    local i, j = t[1], t[2]
    distance[i][j] = 0
end
local function dfs(d, i, j)
    d = d + 1
    local x, y
    x, y = i-1, j
    if x >= 1 and distance[x][y] > d then
        distance[x][y] = d
        dfs(d, x, y)
    end
    x, y = i+1, j
    if x <= H and distance[x][y] > d then
        distance[x][y] = d
        dfs(d, x, y)
    end
    x, y = i, j-1
    if y >= 1 and distance[x][y] > d then
        distance[x][y] = d
        dfs(d, x, y)
    end
    x, y = i, j+1
    if y <= W and distance[x][y] > d then
        distance[x][y] = d
        dfs(d, x, y)
    end
end
for _, t in ipairs(blacks) do
    local i, j = t[1], t[2]
    dfs(0, i, j)
end
local dmax = 0
for i=1, H do
    for j=1, W do
        dmax = math.max(distance[i][j], dmax)
    end
end
print(dmax)


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

------
local H, W = io.read("*n", "*n", "*l")
local grid = {}
for i=1, H do
    grid[i] = str2tbl(io.read("*l"))
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local count = 0
local blacks_used = {}
while true do
    local all_black = true
    local blacks = {}
    for i=1, H do
        for j=1, W do
            local c = grid[i][j]
            if c == '.' then
                all_black = false
            end
            if c == '#' then
                if not blacks_used[i*1000+j] then
                    table.insert(blacks, {i, j})
                    blacks_used[i*1000+j] = true
                end
            end
        end
    end
    if all_black then
        print(count)
        return
    end
    for _, t in ipairs(blacks) do
        local i, j = t[1], t[2]
        if i >= 2 then
            grid[i-1][j] = '#'
        end
        if i <= H - 1 then
            grid[i+1][j] = '#'
        end
        if j >= 2 then
            grid[i][j-1] = '#'
        end
        if j <= W - 1 then
            grid[i][j+1] = '#'
        end
    end
    --[[
    print(count, #blacks)
    for i=1, H do
        print(table.concat(grid[i], ''))
    end
    ]]
    count = count + 1
end


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

------
local H, W = io.read("*n", "*n", "*l")
local grid = {}
for i=1, H do
    grid[i] = str2tbl(io.read("*l"))
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local count = 0
local blacks_used = {}
while true do
    local all_black = true
    local blacks = {}
    for i=1, H do
        for j=1, W do
            local c = grid[i][j]
            if c == '.' then
                all_black = false
                break
            end
            if c == '#' then
                if not blacks_used[i*1000+j] then
                    table.insert(blacks, {i, j})
                    blacks_used[i*1000+j] = true
                end
            end
        end
    end
    if all_black then
        print(count)
        return
    end
    for _, t in ipairs(blacks) do
        local i, j = t[1], t[2]
        if i >= 2 then
            grid[i-1][j] = '#'
        end
        if i <= H - 1 then
            grid[i+1][j] = '#'
        end
        if j >= 2 then
            grid[i][j-1] = '#'
        end
        if j <= W - 1 then
            grid[i][j+1] = '#'
        end
    end
    --[[
    print(count)
    for i=1, H do
        print(table.concat(grid[i], ''))
    end
    ]]
    count = count + 1
end


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

------
local H, W = io.read("*n", "*n", "*l")
local grid = {}
for i=1, H do
    grid[i] = str2tbl(io.read("*l"))
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local count = 0
while true do
    local all_black = true
    for i=1, H do
        for j=1, W do
            local c = grid[i][j]
            if c == '.' then
                all_black = false
                break
            end
        end
    end
    if all_black then
        print(count)
        return
    end
    local blacks = {}
    for i=1, H do
        for j=1, W do
            local c = grid[i][j]
            if c == '#' then
                table.insert(blacks, {i, j})
            end
        end
    end
    for _, t in ipairs(blacks) do
        local i, j = t[1], t[2]
        if i >= 2 then
            grid[i-1][j] = '#'
        end
        if i <= H - 1 then
            grid[i+1][j] = '#'
        end
        if j >= 2 then
            grid[i][j-1] = '#'
        end
        if j <= W - 1 then
            grid[i][j+1] = '#'
        end
    end
    --[[
    print(count)
    for i=1, H do
        print(table.concat(grid[i], ''))
    end
    ]]
    count = count + 1
end


local function str2tbl(s)
    local t = {string.byte(s, 1, #s)}
    for i=1, #t do
        t[i] = string.char(t[i])
    end
    return t
end

------
local H, W = io.read("n", "n", "l")
local grid = {}
for i=1, H do
    grid[i] = str2tbl(io.read("l"))
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local count = 0
while true do
    local all_black = true
    for i=1, H do
        for j=1, W do
            local c = grid[i][j]
            if c == '.' then
                all_black = false
                break
            end
        end
    end
    if all_black then
        print(count)
        return
    end
    local blacks = {}
    for i=1, H do
        for j=1, W do
            local c = grid[i][j]
            if c == '#' then
                table.insert(blacks, {i, j})
            end
        end
    end
    for _, t in ipairs(blacks) do
        local i, j = t[1], t[2]
        if i >= 2 then
            grid[i-1][j] = '#'
        end
        if i <= H - 1 then
            grid[i+1][j] = '#'
        end
        if j >= 2 then
            grid[i][j-1] = '#'
        end
        if j <= W - 1 then
            grid[i][j+1] = '#'
        end
    end
    --[[
    print(count)
    for i=1, H do
        print(table.concat(grid[i], ''))
    end
    ]]
    count = count + 1
end


local function str2tbl(s)
    local t = {string.unpack(string.rep("c1", #s), s)}
    table.remove(t)
    return t
end

local function setdefault(t, v)
    setmetatable(t, {__index = function() return v end})
end

local function read_array(N)
    local t, insert, read = {}, table.insert, io.read
    for i=1, N do insert(t, read("n")) end
    return t
end

local function read(ptn)
    local t = {}
    local ptn = str2tbl(ptn)
    for i=1, #ptn do
        c = ptn[i]
        if c == "n" then
            table.insert(t, io.read("n"))
        elseif c == "L" then
            io.read("l")
        elseif c == "l" then
            table.insert(t, io.read("l"))
        end
    end
    return table.unpack(t)
end

------
local H, W = read("nnL")
local grid = {}
for i=1, H do
    grid[i] = str2tbl(read("l"))
end
--[[
for i=1, H do
    for j=1, W do
        print(i,j, grid[i][j])
    end
end
]]
local count = 0
while true do
    local all_black = true
    for i=1, H do
        for j=1, W do
            local c = grid[i][j]
            if c == '.' then
                all_black = false
                break
            end
        end
    end
    if all_black then
        print(count)
        return
    end
    local blacks = {}
    for i=1, H do
        for j=1, W do
            local c = grid[i][j]
            if c == '#' then
                table.insert(blacks, {i, j})
            end
        end
    end
    for _, t in ipairs(blacks) do
        local i, j = t[1], t[2]
        if i >= 2 then
            grid[i-1][j] = '#'
        end
        if i <= H - 1 then
            grid[i+1][j] = '#'
        end
        if j >= 2 then
            grid[i][j-1] = '#'
        end
        if j <= W - 1 then
            grid[i][j+1] = '#'
        end
    end
    --[[
    print(count)
    for i=1, H do
        print(table.concat(grid[i], ''))
    end
    ]]
    count = count + 1
end


local ior = io.input()
local h, w = ior:read("*n", "*n", "*l")
local map = {}
for i = 1, h * w do map[i] = 0 end
local str = ""

local function getidx(wid, hgt)
  return (hgt - 1) * w + wid
end

local tasks = {}
local tasknum = 0
local done = 0

for i = 1, h do
  str = ior:read()
  for j = 1, w do
    local idx = getidx(j, i)
    if(str:sub(j, j) == ".") then
      map[idx] = 3000
    else
      table.insert(tasks, idx)
      tasknum = tasknum + 1
    end
  end
end

local function walk(src, dst)
  if(map[src] + 1 < map[dst]) then
    map[dst] = map[src] + 1
    table.insert(tasks, dst)
    tasknum = tasknum + 1
  end
end

while(done < tasknum) do
  done = done + 1
  local curidx = tasks[done]
  if(w < curidx) then walk(curidx, curidx - w) end
  if(curidx <= w * (h - 1)) then walk(curidx, curidx + w) end
  if(w ~= 1 and curidx % w ~= 0) then walk(curidx, curidx + 1) end
  if(w ~= 1 and curidx % w ~= 1) then walk(curidx, curidx - 1) end
end
local max = 0
local mma = math.max
for i = 1, h * w do
  max = mma(max, map[i])
end
print(max)


local ior = io.input()
local h, w = ior:read("*n", "*n", "*l")
local map = {}
for i = 1, h * w do map[i] = 0 end
local str = ""

local function getidx(wid, hgt)
  return (hgt - 1) * w + wid
end

local tasks = {}
local tasknum = 0
local done = 0

for i = 1, h do
  str = ior:read()
  for j = 1, w do
    local idx = getidx(i, j)
    if(str:sub(j, j) == ".") then
      map[idx] = 3000
    else
      table.insert(tasks, idx)
      tasknum = tasknum + 1
    end
  end
end

local function walk(src, dst)
  if(map[src] + 1 < map[dst]) then
    map[dst] = map[src] + 1
    table.insert(tasks, dst)
    tasknum = tasknum + 1
  end
end

while(done < tasknum) do
  done = done + 1
  local curidx = tasks[done]
  if(w < curidx) then walk(curidx, curidx - w) end
  if(curidx <= w * (h - 1)) then walk(curidx, curidx + w) end
  if(curidx % w ~= 0) then walk(curidx, curidx + 1) end
  if(curidx % w ~= 1) then walk(curidx, curidx - 1) end
end
local max = 0
local mma = math.max
for i = 1, h * w do
  max = mma(max, map[i])
end
print(max)


local function getgcd(x, y)
  while 0 < x do
    x, y = y % x, x
  end
  return y
end
local n = io.read("*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
local left = {a[1]}
for i = 2, n - 1 do
  left[i] = getgcd(left[i - 1], a[i])
end
local right = {a[n]}
for i = n - 1, 2, -1 do
  right[n - i + 1] = getgcd(right[n - i], a[i])
end
local mmi, mma = math.min, math.max
local ret = mma(left[n - 1], right[n - 1])
for i = 1, n - 2 do
  local cand = getgcd(left[i], right[n - 1 - i])
  ret = mma(ret, cand)
end
print(ret)

Score : 300 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Output

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.


local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = self.func(self.stage[i + 1][j * 2 - 1], self.stage[i + 1][j * 2])
    end
  end
end
SegTree.create = function(self, ary, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.cnt, self.stage, self.size = {1}, {{}}, {}
  while mul < #ary do
    mul, stagenum = mul * 2, stagenum + 1
    self.cnt[stagenum], self.stage[stagenum] = mul, {}
  end
  for i = 1, stagenum do self.size[i] = self.cnt[stagenum + 1 - i] end
  self.stagenum = stagenum
  for i = 1, #ary do self.stage[stagenum][i] = ary[i] end
  for i = #ary + 1, mul do self.stage[stagenum][i] = emptyvalue end
  self:updateAll()
end
SegTree.getRange = function(self, left, right)
  if left == right then return self.stage[self.stagenum][left] end
  local start_stage = 1
  while right - left + 1 < self.size[start_stage] do
    start_stage = start_stage + 1
  end
  local ret = self.emptyvalue
  local tasks = {{start_stage, left, right}}
  while 0 < #tasks do
    local task = tasks[#tasks]
    table.remove(tasks)
    local stage, l, r = task[1], task[2], task[3]
    if (l - 1) % self.size[stage] ~= 0 then
      local newr = mce((l - 1) / self.size[stage]) * self.size[stage]
      table.insert(tasks, {stage + 1, l, mmi(r, newr)})
      l = newr + 1
    end
    if self.size[stage] <= r + 1 - l then
      local pos = mce(l / self.size[stage])
      ret = self.func(ret, self.stage[stage][pos])
      l = l + self.size[stage]
    end
    if l <= r then
      table.insert(tasks, {stage + 1, l, r})
    end
  end
  return ret
end
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = value
  if not silent then
    for i = self.stagenum - 1, 1, -1 do
      local dst = mce(idx / 2)
      local rem = dst * 4 - 1 - idx
      self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
      idx = dst
    end
  end
end
SegTree.new = function(ary, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(ary, func, emptyvalue)
  return obj
end
local function getgcd(x, y)
  while 0 < x do
    x, y = y % x, x
  end
  return y
end
local n = io.read("*n")
local a = {}
for i = 1, n do a[i] = io.read("*n") end
local mma = math.max
local st = SegTree.new(a, function(x, y) return getgcd(x, y) end, 0)
local ret = 1
for i = 1, n do
  local tmp = a[i]
  st:setValue(i, 0)
  ret = mma(ret, st:getRange(1, n))
  st:setValue(i, tmp)
end
print(ret)


-- SegTree
-- Ref: http://tsutaj.hatenablog.com/entry/2017/03/29/204841
local function SegTree(func, ident, vec)
    -- func: binary function
    -- ident: identity element
    -- vec: table

    -- private variables
    -- func, ident are also private variables
    local a = {}
    -- n is smallest power of 2 that is greater than or equal to #vec
    local n = 1
    -- end of private variables
    -- constructor
    do -- just make a scope
        while n < #vec do
            n = n << 1
        end
        local size = 2*n - 1
        for i=1, size do
            a[i] = ident
        end
        for i=1, #vec do
            a[i+n-1] = vec[i]
        end
        for i=n-1,1,-1 do
            a[i] = func(a[2*i], a[2*i+1])
        end
    end
    vec = nil
    -- public member functions
    local self = {}
    self.update = function(idx, val)
        idx = idx + n - 1
        a[idx] = val
        while true do
            idx = idx // 2
            a[idx] = func(a[idx*2], a[idx*2 + 1])
            if idx == 1 then
                break
            end
        end
    end
    self.query = function(left, right)
        -- query to [left, right)
        -- **be careful about right half open interval**
        local function q(k, l, r)
            if r <= left or l >= right then
                return ident
            end
            if l >= left and r <= right then
                return a[k]
            end
            local vl = q(2*k  , l, (l+r)//2)
            local vr = q(2*k+1, (l+r)//2, r)
            return func(vl, vr)
        end
        return q(1, 1, n + 1)
    end
    return self
end

------
local function gcd(a,b)
    if b == 0 then
        return a
    else
        return gcd(b, a % b)
    end
end
----

local N = io.read("n")
local A = {}
for i=1,N do
    A[i] = io.read("n")
end
local st = SegTree(gcd, 0, A)
local maxval = 0
local mathmax = math.max
local query = st.query
for i=1, N do
    local left = query(1, i)
    local right = query(i+1, N+1)
    local g = gcd(left, right)
    maxval = mathmax(maxval, g)
end
print(maxval)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

local function dbgpr_t(tbl, use_pairs)
    if DBG then
        local enum = ipairs
        if use_pairs then
            enum = pairs
        end
        dbgpr(tbl)
        io.write("[dbg]")
        for i,v in enum(tbl) do
            io.write(i)
            io.write(":")
            io.write(tostring(v))
            io.write(" ")
        end
        print("")
    end
end

-- SegTree
-- 参考にしました: http://tsutaj.hatenablog.com/entry/2017/03/29/204841
local SegTree = {}
function SegTree.new(func, ident, vec)
    -- func: binary function
    -- ident: identity element
    -- vec: table
    local self = setmetatable({}, {__index = SegTree})
    self.func = func
    self.ident = ident
    local a = {}
    self.a = a
    local n = 1
    while n < #vec do
        n = n * 2
    end
    -- n is smallest power of 2 that is greater than or equal to #vec
    self.n = n
    local size = 2*n - 1
    for i=1, size do
        a[i] = ident
    end
    -- for verification
    --[[
    for i=1, #vec do
        a[i+n-1] = vec[i]
    end
    for i=n-1,1,-1 do
        a[i] = func(a[2*i], a[2*i+1])
    end
    ]]
    return self
end

function SegTree:update(idx, val)
    local a = self.a
    local func = self.func
    idx = idx + self.n - 1
    a[idx] = val
    while true do
        idx = math.floor(idx / 2)
        a[idx] = func(a[idx*2], a[idx*2 + 1])
        if idx == 1 then
            break
        end
    end
end

function SegTree:query(left, right)
    -- query to [left, right)
    -- **be careful about right half open interval**
    local func = self.func
    local ident = self.ident
    local a = self.a
    local function q(k, l, r)
        if r <= left or l >= right then
            return ident
        end
        if l >= left and r <= right then
            return a[k]
        end
        local h = math.floor((l+r)/2)
        local vl = q(2*k  , l, h)
        local vr = q(2*k+1, h, r)
        return func(vl, vr)
    end
    return q(1, 1, self.n + 1)
end
------
local function gcd(a,b)
    if b == 0 then
        return a
    else
        return gcd(b, a % b)
    end
end
----

local N = io.read("*n")
local A = {}
for i=1,N do
    A[i] = io.read("*n")
end
local st = SegTree.new(gcd, 0, A)

-- for verification
for i=1, #st.a do
    st.a[i] = 0
end
for i=1, N do
    st:update(i, A[i])
end

dbgpr_t(st.a)
local maxval = 0
for i=1, N do
    local left = st:query(1, i)
    local right = st:query(i+1, N+1)
    local g = gcd(left, right)
    dbgpr(i, left, right, g)
    maxval = math.max(maxval, g)
end
print(maxval)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

local function dbgpr_t(tbl, use_pairs)
    if DBG then
        local enum = ipairs
        if use_pairs then
            enum = pairs
        end
        dbgpr(tbl)
        io.write("[dbg]")
        for i,v in enum(tbl) do
            io.write(i)
            io.write(":")
            io.write(tostring(v))
            io.write(" ")
        end
        print("")
    end
end

-- SegTree
-- 参考にしました: http://tsutaj.hatenablog.com/entry/2017/03/29/204841
local SegTree = {}
function SegTree.new(func, ident, vec)
    -- func: binary function
    -- ident: identity element
    -- vec: table
    local self = setmetatable({}, {__index = SegTree})
    self.func = func
    self.ident = ident
    local a = {}
    self.a = a
    local n = 1
    while n < #vec do
        n = n * 2
    end
    -- n is smallest power of 2 that is greater than or equal to #vec
    self.n = n
    local size = 2*n - 1
    for i=1, size do
        a[i] = ident
    end
    -- for verification
    --[[
    for i=1, #vec do
        a[i+n-1] = vec[i]
    end
    for i=n-1,1,-1 do
        a[i] = func(a[2*i], a[2*i+1])
    end
    ]]
    return self
end

function SegTree:update(idx, val)
    local a = self.a
    local func = self.func
    idx = idx + self.n - 1
    a[idx] = val
    while true do
        idx = math.floor(idx / 2)
        a[idx] = func(a[idx*2], a[idx*2 + 1])
        if idx == 1 then
            break
        end
    end
end

function SegTree:query(left, right)
    -- query to [left, right)
    -- **be careful about right half open interval**
    local func = self.func
    local ident = self.ident
    local a = self.a
    local function q(k, l, r)
        if r <= left or l >= right then
            return ident
        end
        if l >= left and r <= right then
            return a[k]
        end
        local h = math.floor((l+r)/2)
        local vl = q(2*k  , l, h)
        local vr = q(2*k+1, h, r)
        return func(vl, vr)
    end
    return q(1, 1, self.n + 1)
end
------
local function gcd(a,b)
    if b == 0 then
        return a
    else
        return gcd(b, a % b)
    end
end
----

local N = io.read("n")
local A = {}
for i=1,N do
    A[i] = io.read("n")
end
local st = SegTree.new(gcd, 0, A)

-- for verification
for i=1, #st.a do
    st.a[i] = 0
end
for i=1, N do
    st:update(i, A[i])
end

dbgpr_t(st.a)
local maxval = 0
for i=1, N do
    local left = st:query(1, i)
    local right = st:query(i+1, N+1)
    local g = gcd(left, right)
    dbgpr(i, left, right, g)
    maxval = math.max(maxval, g)
end
print(maxval)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

local function dbgpr_t(tbl, use_pairs)
    if DBG then
        local enum = ipairs
        if use_pairs then
            enum = pairs
        end
        dbgpr(tbl)
        io.write("[dbg]")
        for i,v in enum(tbl) do
            io.write(i)
            io.write(":")
            io.write(tostring(v))
            io.write(" ")
        end
        print("")
    end
end

-- SegTree
-- 参考にしました: http://tsutaj.hatenablog.com/entry/2017/03/29/204841
local SegTree = {}
function SegTree.new(func, ident, vec)
    -- func: binary function
    -- ident: identity element
    -- vec: table
    local self = setmetatable({}, {__index = SegTree})
    self.func = func
    self.ident = ident
    local a = {}
    self.a = a
    local n = 1
    while n < #vec do
        n = n << 1
    end
    -- n is smallest power of 2 that is greater than or equal to #vec
    self.n = n
    local size = 2*n - 1
    for i=1, size do
        a[i] = ident
    end
    -- for verification
    --[[
    for i=1, #vec do
        a[i+n-1] = vec[i]
    end
    for i=n-1,1,-1 do
        a[i] = func(a[2*i], a[2*i+1])
    end
    ]]
    return self
end

function SegTree:update(idx, val)
    local a = self.a
    local func = self.func
    idx = idx + self.n - 1
    a[idx] = val
    while true do
        idx = idx // 2
        a[idx] = func(a[idx*2], a[idx*2 + 1])
        if idx == 1 then
            break
        end
    end
end

function SegTree:query(left, right)
    -- query to [left, right)
    -- **be careful about right half open interval**
    local func = self.func
    local ident = self.ident
    local a = self.a
    local function q(k, l, r)
        if r <= left or l >= right then
            return ident
        end
        if l >= left and r <= right then
            return a[k]
        end
        local vl = q(2*k  , l, (l+r)//2)
        local vr = q(2*k+1, (l+r)//2, r)
        return func(vl, vr)
    end
    return q(1, 1, self.n + 1)
end
------
local function gcd(a,b)
    if b == 0 then
        return a
    else
        return gcd(b, a % b)
    end
end
----

local N = io.read("n")
local A = {}
for i=1,N do
    A[i] = io.read("n")
end
local st = SegTree.new(gcd, 0, A)

-- for verification
for i=1, #st.a do
    st.a[i] = 0
end
for i=1, N do
    st:update(i, A[i])
end

dbgpr_t(st.a)
local maxval = 0
for i=1, N do
    local left = st:query(1, i)
    local right = st:query(i+1, N+1)
    local g = gcd(left, right)
    dbgpr(i, left, right, g)
    maxval = math.max(maxval, g)
end
print(maxval)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

local function dbgpr_t(tbl, use_pairs)
    if DBG then
        local enum = ipairs
        if use_pairs then
            enum = pairs
        end
        dbgpr(tbl)
        io.write("[dbg]")
        for i,v in enum(tbl) do
            io.write(i)
            io.write(":")
            io.write(tostring(v))
            io.write(" ")
        end
        print("")
    end
end

-- SegTree
-- 参考にしました: http://tsutaj.hatenablog.com/entry/2017/03/29/204841
local SegTree = {}
function SegTree.new(func, ident, vec)
    -- func: binary function
    -- ident: identity element
    -- vec: table
    local self = setmetatable({}, {__index = SegTree})
    self.func = func
    self.ident = ident
    local a = {}
    self.a = a
    local n = 1
    while n < #vec do
        n = n << 1
    end
    -- n is smallest power of 2 that is greater than or equal to #vec
    self.n = n
    local size = 2*n - 1
    for i=1, size do
        a[i] = ident
    end
    for i=1, #vec do
        a[i+n-1] = vec[i]
    end
    for i=n-1,1,-1 do
        a[i] = func(a[2*i], a[2*i+1])
    end
    return self
end

function SegTree:update(idx, val)
    local a = self.a
    local func = self.func
    idx = idx + self.n - 1
    a[idx] = val
    while true do
        idx = idx // 2
        a[idx] = func(a[idx*2], a[idx*2 + 1])
        if idx == 1 then
            break
        end
    end
end

function SegTree:query(left, right)
    -- query to [left, right)
    -- **be careful about right half open interval**
    local func = self.func
    local ident = self.ident
    local a = self.a
    local function q(k, l, r)
        if r <= left or l >= right then
            return ident
        end
        if l >= left and r <= right then
            return a[k]
        end
        local vl = q(2*k  , l, (l+r)//2)
        local vr = q(2*k+1, (l+r)//2, r)
        return func(vl, vr)
    end
    return q(1, 1, self.n + 1)
end
------
local function gcd(a,b)
    if b == 0 then
        return a
    else
        return gcd(b, a % b)
    end
end
----

local N = io.read("n")
local A = {}
for i=1,N do
    A[i] = io.read("n")
end
local st = SegTree.new(gcd, 0, A)
--[[
-- for verification
for i=1, #st.a do
    st.a[i] = 0
end
for i=1, N do
    st:update(i, A[i])
end
]]
dbgpr_t(st.a)
local maxval = 0
for i=1, N do
    local left = st:query(1, i)
    local right = st:query(i+1, N+1)
    local g = gcd(left, right)
    dbgpr(i, left, right, g)
    maxval = math.max(maxval, g)
end
print(maxval)


local ior = io.read
local n = ior("*n")
local a = {}
for i = 1, n do a[i] = io.read("*n") end

local function getgcd(x, y)
  while(0 < x and 0 < y) do
    if(x < y) then y = y % x else x = x % y end
  end
  return math.max(x, y)
end

local mac = math.ceil
local mam = math.max

local mesh = 60

local groups = mac(n / mesh)
local groupgcd = {}
local group_inv_gcd = {}
for i = 1, groups do
  groupgcd[i] = 0
  group_inv_gcd[i] = 0
end

for i = 1, n do
  local g = mac(i / mesh)
  groupgcd[g] = getgcd(groupgcd[g], a[i])
end

for i = 1, groups do
  for j = 1, groups do
    if(i ~= j) then
      group_inv_gcd[i] = getgcd(group_inv_gcd[i], groupgcd[j])
    end
  end
end

local ret = 0

for i = 1, n do
  local g = mac(i / mesh)
  local stt = 1 + (g - 1) * mesh
  local last = (g == groups and n or g * mesh)
  local cand = group_inv_gcd[g]
  for j = stt, last do
    if(j ~= i) then
      cand = getgcd(cand, a[j])
    end
  end
  ret = mam(ret, cand)
end
print(ret)


local function gcd(a,b)
    if b == 0 then
        return a
    else
        return gcd(b, a % b)
    end
end

local function gcdmany(tbl)
    local ans = tbl[1]
    for i=2,#tbl do
        ans = gcd(ans, tbl[i])
    end
    return ans
end

----

local N = io.read("n")
local A = {} for i=1,N do A[i] = io.read("n") end

local L, R = {}, {}
L[1] = A[1]
for i=2, N do
    L[i] = gcd(L[i-1], A[i])
end
R[N] = A[N]
for i=N-1, 1,-1 do
    R[i] = gcd(R[i+1], A[i])
end

local maxval = 0
maxval = math.max(maxval, R[2])
for i=2, N-1 do
    local g = gcd(L[i-1], R[i+1])
    maxval = math.max(maxval, g)
end
maxval = math.max(maxval, L[N-1])

print(maxval)


function gcd(x, y, z)
	return x<=z and z or y == 0 and x or gcd(y, x % y, z)
end
n = io.read"*n"
a = {}
r=0
for i=1,n do
	a[i] = io.read"*n"
	t = {table.unpack(a)}
	t[i] = a[i+1] or a[i-1]
	for j=1,n-1 do
		t[1] = gcd(t[1], t[j+1], r)
	end
	r = t[1]
end
print(r)


function gcd(x, y, z)
	return x<z and z or y == 0 and x or gcd(y, x % y, z)
end
n = io.read"*n"
a = {}
for i=1,n do
	a[i] = io.read"*n"
end
r=0
for i=1,n do
	t = {table.unpack(a)}
	t[i] = a[i+1] or a[i-1]
	for j=1,n-1 do
		t[1] = gcd(t[1], t[j+1], r)
	end
	r = t[1]
end
print(r)


function gcd(x, y)
	return y == 0 and x or gcd(y, x % y)
end
n = io.read"*n"
a = {}
for i=1,n do
	a[i] = io.read"*n"
end
r=0
for i=1,n do
	t = {table.unpack(a)}
	t[i] = a[i+1] or a[i-1]
	for j=1,n-1 do
		t[1] = gcd(t[1],t[j+1])
	end
	r = t[1]
end
print(r)


function gcd(x, y, z)
	return (x<z) and z or y == 0 and x or gcd(y, x % y, z)
end
n = io.read"*n"
a = {io.read((("*n"):rep(n)):match(("(*n)"):rep(n)))}
r=0
for i=1,n do
	t = {table.unpack(a)}
	t[i]=a[i+1] or a[i-1]
	for j=1,n-1 do
		t[1]=gcd(t[1],t[j+1],r)
	end
	r=t[1]
end
print(r)


function gcd(x, y)
	return y == 0 and x or gcd(y, x % y)
end
n = io.read"*n"
a = {io.read((("*n"):rep(n)):match(("(*n)"):rep(n)))}
r = {}
for i=1,n do
	t = {table.unpack(a)}
	t[i]=a[i+1] or a[i-1]
	r[i]=t[1]
	for j=1,n-1 do
		r[i]=gcd(r[i],t[j+1])
	end
end
print(math.max(table.unpack(r)))


local ior = io.read
local n = ior("*n")
local a = {}
for i = 1, n do a[i] = io.read("*n") end

local function getgcd(x, y)
  while(0 < x and 0 < y) do
    if(x < y) then y = y % x else x = x % y end
  end
  return math.max(x, y)
end

local mac = math.ceil
local mam = math.max

local mesh = 500

local groups = mac(n / mesh)
local groupgcd = {}
local group_inv_gcd = {}
for i = 1, groups do
  groupgcd[i] = 0
  group_inv_gcd[i] = 0
end

for i = 1, n do
  local g = mac(i / mesh)
  groupgcd[g] = getgcd(groupgcd[g], a[i])
end

for i = 1, groups do
  for j = 1, groups do
    if(i ~= j) then
      group_inv_gcd[i] = getgcd(group_inv_gcd[i], groupgcd[j])
    end
  end
end

local ret = 0

for i = 1, n do
  local g = mac(i / mesh)
  local stt = 1 + (g - 1) * mesh
  local last = (g == groups and n or g * mesh)
  local cand = group_inv_gcd[g]
  for j = stt, last do
    if(j ~= i) then
      cand = getgcd(cand, a[j])
    end
  end
  ret = mam(ret, cand)
end
print(ret)


local ior = io.read
local n = ior("*n")
local a = {}
for i = 1, n do a[i] = io.read("*n") end

local function getgcd(x, y)
  while(0 < x and 0 < y) do
    if(x < y) then y = y % x else x = x % y end
  end
  return math.max(x, y)
end

local mac = math.ceil
local mam = math.max

local groups = mac(n / 1000)
local groupgcd = {}
local group_inv_gcd = {}
for i = 1, groups do
  groupgcd[i] = 0
  group_inv_gcd[i] = 0
end

for i = 1, n do
  local g = mac(i / 1000)
  groupgcd[g] = getgcd(groupgcd[g], a[i])
end

for i = 1, groups do
  for j = 1, groups do
    if(i ~= j) then
      group_inv_gcd[i] = getgcd(group_inv_gcd[i], groupgcd[j])
    end
  end
end

local ret = 0

for i = 1, n do
  local g = mac(i / 1000)
  local stt = 1 + (g - 1) * 1000
  local last = (g == groups and n or g * 1000)
  local cand = group_inv_gcd[g]
  for j = stt, last do
    if(j ~= i) then
      cand = getgcd(cand, a[j])
    end
  end
  ret = mam(ret, cand)
end
print(ret)


local function gcd(a,b)
    if b == 0 then
        return a
    else
        return gcd(b, a % b)
    end
end

local function gcdmany(tbl)
    local ans = tbl[1]
    for i=2,#tbl do
        ans = gcd(ans, tbl[i])
    end
    return ans
end

local function lcm(a, b)
    return a // gcd(a, b) * b
end

local function lcmmany(tbl)
    local ans = tbl[1]
    for i=2, #tbl do
        ans = lcm(ans, tbl[i])
    end
    return ans
end

-----
local function gcdmany_notx(tbl, x)
    local ans
    if x ~= 1 then
        ans = tbl[1]
        for i=2,#tbl do
            if i ~= x then
                ans = gcd(ans, tbl[i])
            end
        end
    else
        -- x == 1
        ans = tbl[2]
        for i=3,#tbl do
            ans = gcd(ans, tbl[i])
        end
    end
    return ans
end

local N = io.read("n")
local A = {} for i=1,N do A[i] = io.read("n") end

local maxval = 0
for i=1, N do
    local g = gcdmany_notx(A, i)
    maxval = math.max(maxval, g)
end
print(maxval)


local mod = 998244353
local mma, mmi = math.max, math.min
local mfl = math.floor

local function bmul(x, y)
  local x0, y0 = x % 31596, y % 31596
  local x1, y1 = mfl(x / 31596), mfl(y / 31596)
  return (x1 * y1 * 62863 + (x1 * y0 + x0 * y1) * 31596 + x0 * y0) % mod
end

local function badd(x, y)
  return (x + y) % mod
end

local function bsub(x, y)
  return x < y and x - y + mod or x - y
end

local function modpow(src, pow)
  local res = 1
  while 0 < pow do
    if pow % 2 == 1 then
      res = bmul(res, src)
      pow = pow - 1
    end
    src = bmul(src, src)
    pow = mfl(pow / 2)
  end
  return res
end

local n = io.read("*n")
local a = {}
local tot = 0
for i = 1, n do
  a[i] = io.read("*n")
  tot = tot + a[i]
end
local htot = mfl(tot / 2)
local dp = {}
local single = {}
local curmax = 0
for i = 1, htot do
  dp[i] = 0
  single[i] = 0
end
for i = 1, n do
  local ai = a[i]
  local lim = mmi(curmax, htot - ai)
  for j = lim, 1, -1 do
    dp[j + ai] = badd(dp[j + ai], bmul(2, dp[j]))
    single[j + ai] = badd(single[j + ai], single[j])
  end
  if ai <= htot then
    dp[ai] = badd(dp[ai], 2)
    single[ai] = badd(single[ai], 1)
  end
  curmax = curmax + ai
end
local ret = modpow(3, n)
if tot % 2 == 0 then
  local rmsum = 1
  for i = 1, htot do
    rmsum = badd(rmsum, dp[i])
  end
  rmsum = bsub(rmsum, single[htot])
  rmsum = bmul(rmsum, 3)
  ret = bsub(ret, rmsum)
else
  local rmsum = 1
  for i = 1, htot do
    rmsum = badd(rmsum, dp[i])
  end
  rmsum = bmul(rmsum, 3)
  ret = bsub(ret, rmsum)
end
print(ret)

Score : 600 points

Problem Statement

You are given N integers. The i-th integer is a_i.
Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied:

Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area whose sides have lengths R, G and B.

Constraints

3 \leq N \leq 300

1 \leq a_i \leq 300(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
:
a_N

Output

Print the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the condition is satisfied.

Sample Input 1

4
1
1
1
2

Sample Output 1

18

We can only paint the integers so that the lengths of the sides of the triangle will be 1, 2 and 2, and there are 18 such ways.

Sample Input 2

6
1
3
2
3
5
2

Sample Output 2

150

Sample Input 3

20
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9
3
2
3
8
4

Sample Output 3

563038556


local mod = 998244353
local mma, mmi = math.max, math.min
local mfl = math.floor

local function bmul(x, y)
  local x0, y0 = x % 31596, y % 31596
  local x1, y1 = mfl(x / 31596), mfl(y / 31596)
  return (x1 * y1 * 62863 + (x1 * y0 + x0 * y1) * 31596 + x0 * y0) % mod
end

local function badd(x, y)
  return (x + y) % mod
end

local function bsub(x, y)
  return x < y and x - y + mod or x - y
end

local function modpow(src, pow)
  local res = 1
  while 0 < pow do
    if pow % 2 == 1 then
      res = bmul(res, src)
      pow = pow - 1
    end
    src = bmul(src, src)
    pow = mfl(pow / 2)
  end
  return res
end

local n = io.read("*n")
local a = {}
local tot = 0
for i = 1, n do
  a[i] = io.read("*n")
  tot = tot + a[i]
end
local htot = mfl(tot / 2)
local dp = {}
local single = {}
local curmax = 0
for i = 1, htot do
  dp[i] = 0
  single[i] = 0
end
for i = 1, n do
  local ai = a[i]
  local lim = mmi(curmax, htot - ai)
  for j = lim, 1, -1 do
    dp[j + ai] = badd(dp[j + ai], bmul(2, dp[j]))
    single[j + ai] = badd(single[j + ai], single[j])
  end
  dp[ai] = badd(dp[ai], 2)
  single[ai] = badd(single[ai], 1)
  curmax = curmax + ai
end
local ret = modpow(3, n)
if tot % 2 == 0 then
  local rmsum = 1
  for i = 1, htot do
    rmsum = badd(rmsum, dp[i])
  end
  rmsum = bsub(rmsum, single[htot])
  rmsum = bmul(rmsum, 3)
  ret = bsub(ret, rmsum)

else
  local rmsum = 1
  for i = 1, htot do
    rmsum = badd(rmsum, dp[i])
  end
  rmsum = bmul(rmsum, 3)
  ret = bsub(ret, rmsum)
end
print(ret)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    elseif n % 2 == 0 then
        return modpow(b * b % m, n//2, m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("n")
    S = S + a[i]
end

local function default0(t)
    local mt = {
        __index = function(t,k)
            return 0
        end
    }
    setmetatable(t, mt)
end

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    local src = {}
    default0(src)
    src[0] = 1
    for i=1,N do
        local cur = a[i]
        local dst = {}
        default0(dst)
        for k,v in pairs(src) do
            dst[k] = v
        end
        for k,v in pairs(src) do
            dst[k+cur] = (v + dst[k+cur]) % MOD
        end
        src, dst = dst, src
    end
    return src[S//2]
end

-- ∑A >= S/2
local function getX()
    local src = {}
    default0(src)
    src[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        local dst = {}
        default0(dst)
        curmax = curmax + cur
        for k,v in pairs(src) do
            dst[k] = 2 * v % MOD
        end
        for k,v in pairs(src) do
            dst[k+cur] = (v + dst[k+cur]) % MOD
        end
        src, dst = dst, src
    end
    local sum = 0
    for s = math.ceil(S/2), curmax, 1 do
        sum = sum + src[s]
    end
    return sum
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
local ans = (Total - (3 * X) + (3 * Y)) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("*n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("*n")
    S = S + a[i]
end

local function fill90000(t, v)
    for i=1,90000 do
        t[i] = v
    end
end

local function default0(t)
    local mt = {
        __index = function(t,k)
            return 0
        end
    }
    setmetatable(t, mt)
end

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    local cache = {}
    --default0(cache)
    fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (cache[s] + cache[s-cur]) % MOD
        end
    end
    return cache[math.floor(S/2)]
end

-- ∑A >= S/2
local function getX()
    local cache = {}
    --default0(cache)
    fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (2 * cache[s] + cache[s-cur]) % MOD
        end
        for s=cur-1,0,-1 do
            cache[s] = 2 * cache[s] % MOD
        end
    end
    local sum = 0
    for s = math.ceil(S/2), curmax, 1 do
        sum = sum + cache[s]
    end
    return sum
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    elseif n % 2 == 0 then
        return modpow(b * b % m, n//2, m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("n")
    S = S + a[i]
end

local function fill90000(t, v)
    for i=1,90000 do
        t[i] = v
    end
end

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    local cache = {}
    fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (cache[s] + cache[s-cur]) % MOD
        end
    end
    return cache[S//2]
end

-- ∑A >= S/2
local function getX()
    local cache = {}
    fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (2 * cache[s] + cache[s-cur]) % MOD
        end
        for s=cur-1,0,-1 do
            cache[s] = 2 * cache[s] % MOD
        end
    end
    local sum = 0
    for s = math.ceil(S/2), curmax, 1 do
        sum = sum + cache[s]
    end
    return sum
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
local ans = (Total - (3 * X) + (3 * Y)) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("*n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("*n")
    S = S + a[i]
end

local function fill90000(t, v)
    for i=1,900000 do
        t[i] = v
    end
end

local function default0(t)
    local mt = {
        __index = function(t,k)
            return 0
        end
    }
    setmetatable(t, mt)
end

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    local cache = {}
    default0(cache)
    --fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (cache[s] + cache[s-cur]) % MOD
        end
    end
    return cache[math.floor(S/2)]
end

-- ∑A >= S/2
local function getX()
    local cache = {}
    default0(cache)
    --fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (2 * cache[s] + cache[s-cur]) % MOD
        end
        for s=cur-1,0,-1 do
            cache[s] = 2 * cache[s] % MOD
        end
    end
    local sum = 0
    for s = math.ceil(S/2), curmax, 1 do
        sum = sum + cache[s]
    end
    return sum
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("*n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("*n")
    S = S + a[i]
end

local function fill90000(t, v)
    for i=1,900000 do
        t[i] = v
    end
end

local function default0(t)
    local mt = {
        __index = function(t,k)
            return 0
        end
    }
    setmetatable(t, mt)
end

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    local cache = {}
    --default0(cache)
    fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (cache[s] + cache[s-cur]) % MOD
        end
    end
    return cache[math.floor(S/2)]
end

-- ∑A >= S/2
local function getX()
    local cache = {}
    --default0(cache)
    fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (2 * cache[s] + cache[s-cur]) % MOD
        end
        for s=cur-1,0,-1 do
            cache[s] = 2 * cache[s] % MOD
        end
    end
    local sum = 0
    for s = math.ceil(S/2), curmax, 1 do
        sum = sum + cache[s]
    end
    return sum
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    elseif n % 2 == 0 then
        return modpow(b * b % m, n//2, m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local AMAX = 300
local N = io.read("n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("n")
    S = S + a[i]
end

local function fill90000(t, v)
    for i=1,900000 do
        t[i] = v
    end
end

local function default0(t)
    local mt = {
        __index = function(t,k)
            return 0
        end
    }
    setmetatable(t, mt)
end

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    local cache = {}
    default0(cache)
    --fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (cache[s] + cache[s-cur]) % MOD
        end
    end
    return cache[S//2]
end

-- ∑A >= S/2
local function getX()
    local cache = {}
    --fill90000(cache, 0)
    default0(cache)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (2 * cache[s] + cache[s-cur]) % MOD
        end
        for s=cur-1,0,-1 do
            cache[s] = 2 * cache[s] % MOD
        end
    end
    local sum = 0
    for s = math.ceil(S/2), curmax, 1 do
        sum = sum + cache[s]
    end
    return sum
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
local ans = (Total - (3 * X) + (3 * Y)) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    elseif n % 2 == 0 then
        return modpow(b * b % m, n//2, m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local AMAX = 300
local N = io.read("n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("n")
    S = S + a[i]
end

local function fill90000(t, v)
    for i=1,900000 do
        t[i] = v
    end
end

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    local cache = {}
    fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (cache[s] + cache[s-cur]) % MOD
        end
        --[[
        for s=cur-1,0,-1 do
            cache[s] = cache[s]
        end
        ]]
    end
    return cache[S//2]
end

-- ∑A >= S/2
local function getX()
    local cache = {}
    fill90000(cache, 0)
    cache[0] = 1
    local curmax = 0
    -- math.ceil(S/2), S
    for i=1,N do
        local cur = a[i]
        curmax = curmax + cur
        for s=curmax,cur,-1 do
            cache[s] = (2 * cache[s] + cache[s-cur]) % MOD
        end
        for s=cur-1,0,-1 do
            cache[s] = 2 * cache[s] % MOD
        end
    end
    local sum = 0
    for s = math.ceil(S/2), curmax, 1 do
        sum = sum + cache[s]
    end
    return sum
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
local ans = (Total - (3 * X) + (3 * Y)) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end
--[[
local function xxxmemoize(f)
    local cache = {}
    return function(i, s)
        if s < 0 then
            return 0
        end
        local k = (i * 100000) + s
        if cache[k] then
            return cache[k]
        end
        local r = f(i, s)
        cache[k] = r
        return r
    end
end
]]

local function memoize(f)
    local cache = {}
    -- http://www.lua.org/doc/jucs05.pdf -- 4 Tables
    -- Make keys contiguous integer so that elements always reside array part
    for i=0, 301 * 90001 do
        cache[i] = -1
    end
    -- i=0,s=0
    cache[0] = 1
    -- i=0,s!=0
    for i=1, 90000 do
        cache[i] = 0
    end
    return function(i, s)
        if s < 0 then
            return 0
        end
        local k = (i * 90001) + s
        if cache[k] >= 0 then
            return cache[k]
        end
        local r = f(i, s)
        cache[k] = r
        return r
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    --elseif n % 2 == 0 then
    --    return modpow(b * b % m, math.floor(n/2), m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("*n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("*n")
    S = S + a[i]
end

local combh
combh = memoize(function(i, s)
    --[[
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    ]]
    --print(i, s, a[i])
    return (combh(i - 1, s - a[i]) + combh(i - 1, s)) % MOD
end)

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    return combh(N, math.floor(S/2))
end

local combgeh
combgeh = memoize(function(i, s)
    --[[
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    ]]
    return (combgeh(i - 1, s - a[i]) + combgeh(i - 1, s) * 2) % MOD
end)

-- ∑A >= S/2
local function getX()
    local sum = 0
    for s = math.ceil(S/2), S, 1 do
        --local c = combgeh(N, s)
        --dbgpr("s,c", s, c)
        sum = (sum + combgeh(N, s)) --% MOD
    end
    return sum % MOD
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
--local ans = (Total - (3 * X) + (3 * Y)) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

--
local function memoize(f)
    local cache = {}
    return function(i, s)
        if s < 0 then
            return 0
        end
        local k = (i * 100000) + s
        if cache[k] then
            return cache[k]
        end
        local r = f(i, s)
        cache[k] = r
        return r
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    --elseif n % 2 == 0 then
    --    return modpow(b * b % m, math.floor(n/2), m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("*n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("*n")
    S = S + a[i]
end

local combh
combh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    --print(i, s, a[i])
    local r = combh(i - 1, s - a[i])
    r = r + combh(i - 1, s)
    return r % MOD
end)

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    return combh(N, math.floor(S/2))
end

local combgeh
combgeh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    local r = combgeh(i - 1, s - a[i])
    r = r + (combgeh(i - 1, s) * 2) -- % MOD
    return r % MOD
end)

-- ∑A >= S/2
local function getX()
    local sum = 0
    for s = math.ceil(S/2), S, 1 do
        local c = combgeh(N, s)
        --dbgpr("s,c", s, c)
        sum = (sum + c) --% MOD
    end
    return sum % MOD
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
--local ans = (Total - (3 * X) + (3 * Y)) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

--
local function memoize(f)
    local cache = {}
    return function(i, s)
        if s < 0 then
            return 0
        end
        local k = (i * 100000) + s
        if cache[k] then
            return cache[k]
        end
        local r = f(i, s)
        cache[k] = r
        return r
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    elseif n % 2 == 0 then
        return modpow(b * b % m, math.floor(n/2), m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("*n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("*n")
    S = S + a[i]
end

local combh
combh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    --print(i, s, a[i])
    local r = combh(i - 1, s - a[i])
    r = r + combh(i - 1, s)
    return r % MOD
end)

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    return combh(N, math.floor(S/2))
end

local combgeh
combgeh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    local r = combgeh(i - 1, s - a[i])
    r = r + (combgeh(i - 1, s) * 2) -- % MOD
    return r % MOD
end)

-- ∑A >= S/2
local function getX()
    local sum = 0
    for s = math.ceil(S/2), S, 1 do
        local c = combgeh(N, s)
        --dbgpr("s,c", s, c)
        sum = (sum + c) --% MOD
    end
    return sum % MOD
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
--local ans = (Total - (3 * X) + (3 * Y)) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

--
local function memoize(f)
    local cache = {}
    return function(i, s)
        local k = (i * 100000) + s
        if cache[k] then
            return cache[k]
        end
        local r = f(i, s)
        cache[k] = r
        return r
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    elseif n % 2 == 0 then
        return modpow(b * b % m, math.floor(n/2), m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("*n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("*n")
    S = S + a[i]
end

local combh
combh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    --print(i, s, a[i])
    local r = combh(i - 1, s - a[i])
    r = r + combh(i - 1, s)
    return r % MOD
end)

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    return combh(N, math.floor(S/2))
end

local combgeh
combgeh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    local r = combgeh(i - 1, s - a[i])
    r = r + (combgeh(i - 1, s) * 2) -- % MOD
    return r % MOD
end)

-- ∑A >= S/2
local function getX()
    local sum = 0
    for s = math.ceil(S/2), S, 1 do
        local c = combgeh(N, s)
        --dbgpr("s,c", s, c)
        sum = (sum + c) --% MOD
    end
    return sum % MOD
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
--local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
local ans = (Total - (3 * X) + (3 * Y)) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

--
local function memoize(f)
    local cache = {}
    return function(i, s)
        local k = (i * 100000) + s
        if cache[k] then
            return cache[k]
        end
        local r = f(i, s)
        cache[k] = r
        return r
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    elseif n % 2 == 0 then
        return modpow(b * b % m, n/2, m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("*n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("*n")
    S = S + a[i]
end

local combh
combh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    --print(i, s, a[i])
    local r = combh(i - 1, s - a[i])
    r = r + combh(i - 1, s)
    return r % MOD
end)

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    return combh(N, math.floor(S/2))
end

local combgeh
combgeh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    local r = combgeh(i - 1, s - a[i])
    r = r + (combgeh(i - 1, s) * 2) -- % MOD
    return r % MOD
end)

-- ∑A >= S/2
local function getX()
    local sum = 0
    for s = math.ceil(S/2), S, 1 do
        local c = combgeh(N, s)
        --dbgpr("s,c", s, c)
        sum = (sum + c) --% MOD
    end
    return sum % MOD
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
--local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
local ans = (Total - (3 * X) + (3 * Y)) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

--
local function memoize(f)
    local cache = {}
    return function(i, s)
        local k = (i<<17) + s
        if cache[k] then
            return cache[k]
        end
        local r = f(i, s)
        cache[k] = r
        return r
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    elseif n % 2 == 0 then
        return modpow(b * b % m, n//2, m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("n")
    S = S + a[i]
end

local combh
combh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    --print(i, s, a[i])
    local r = combh(i - 1, s - a[i])
    r = r + combh(i - 1, s)
    return r % MOD
end)

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    return combh(N, S//2)
end

local combgeh
combgeh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    local r = combgeh(i - 1, s - a[i])
    r = r + (combgeh(i - 1, s) * 2) -- % MOD
    return r % MOD
end)

-- ∑A >= S/2
local function getX()
    local sum = 0
    for s = math.ceil(S/2), S, 1 do
        local c = combgeh(N, s)
        --dbgpr("s,c", s, c)
        sum = (sum + c) --% MOD
    end
    return sum % MOD
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
--dbgpr(Total, X, Y)
--local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
local ans = (Total - (3 * X) + (3 * Y)) % MOD
print(ans)


local DBG = false
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end

--
local function memoize(f)
    local cache = {}
    local function key(...)
        local args = {...}
        local k = tostring(args[1])
        for i=2,#args do
            k = k .. "*" .. tostring(args[i])
        end
        return k
    end
    return function(...)
        local k = key(...)
        if cache[k] then
            return cache[k]
        end
        local r = f(...)
        cache[k] = r
        return r
    end
end

-- returns (b^n) % m
local function modpow(b, n, m)
    if n == 0 then
        return 1
    elseif n % 2 == 0 then
        return modpow(b * b % m, n//2, m) % m
    else
        return b * modpow(b, n - 1, m) % m
    end
end

---
local MOD = 998244353
local N = io.read("n")
local a = {}
local S = 0
for i=1,N do
    a[i] = io.read("n")
    S = S + a[i]
end

local combh
combh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    --print(i, s, a[i])
    local r = combh(i - 1, s - a[i])
    r = r + combh(i - 1, s)
    return r % MOD
end)

-- ∑A = S/2 and ∑B = S/2 and ∑C = 0
local function getY()
    if S % 2 == 1 then
        return 0
    end
    return combh(N, S//2)
end

local combgeh
combgeh = memoize(function(i, s)
    if i == 0 then
        if s == 0 then
            return 1
        else
            return 0
        end
    end
    local r = combgeh(i - 1, s - a[i])
    r = r + (combgeh(i - 1, s) * 2) % MOD
    return r % MOD
end)

-- ∑A >= S/2
local function getX()
    local sum = 0
    for s = math.ceil(S/2), S, 1 do
        local c = combgeh(N, s)
        dbgpr("s,c", s, c)
        sum = (sum + c) % MOD
    end
    return sum
end

local X, Y = getX(), getY()
local Total = modpow(3, N, MOD)
dbgpr(Total, X, Y)
local ans = (Total - (3 * X) % MOD + (3 * Y) % MOD) % MOD
print(ans)


Score : 100 points

Problem Statement

Takahashi likes the sound when he buys a drink from a vending machine.

That sound can be heard by spending A yen (the currency of Japan) each time.

Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time.

How many times will he hear the sound?

Constraints

All values in input are integers.

1 \leq A, B, C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times Takahashi will hear his favorite sound.

Sample Input 1

2 11 4

Sample Output 1

4

Since he has not less than 8 yen, he will hear the sound four times and be satisfied.

Sample Input 2

3 9 5

Sample Output 2

3

He may not be able to be satisfied.

Sample Input 3

100 1 10

Sample Output 3

0


a, b, c = io.read("*n", "*n", "n")
print(math.min(b // a, c))


local a, b, c = io.read("*n", "*n", "*n")
print(math.min(c, b // a))


val = {}
for i=1, 3 do
    val[i]=tonumber(io.read())
    print(val[i]+1)
end

if val[1]*val[3]>=val[2] then
	print(val[3])
else
	print(math.floor(val[2]/val[1]))
end


val = {}
val = io.read()

if val[1]*val[3]>=val[2] then
	print(c)
else
	print(math.floor(val[2]/val[1]))
end


io.read(a, b, c)

if a*c>=b then
	print(c)
else
	print(math.floor(b/a))
end


io.io.write(a, b, c)

if a*c>=b then
	print(c)
else
	print(math.floor(b/a))
end


A,B,C=io.read("n","n","n")
if B//A>=C then
  print(C)
  else
  print(B//A)
end


A,B,C=io.rear("n","n","n")
if B//A>=C then
  print(C)
  else
  print(B//A)
end


A=io.rear("n")
B=io.rear("n")
C=io.rear("n")
if B//A>=C then
  print(C)
  else
  print(B//A)
end


a,b,c=io.read():match("(.+)%s(.+)%s(.+)")
x=1
d={}
for i=1,100 do
  if a%i==0 and b%i==0 then
    table.insert(d,i)
  end
end
print(d[#d-c+1])


a,b,c = io.read("n","n","n")
q = b // a
if (q > c) then
    print(c)
else
    print(q)
end


local n=io.read("n")
local h={}
for i=1,n do
    h[i]=io.read("n")
end

local INF=math.maxinteger
local dp={0,math.abs(h[2]-h[1])}
for i=3,n do
    dp[i]=INF
end
for i=3,n do
    dp[i]=math.min(dp[i],dp[i-1]+math.abs(h[i]-h[i-1]))
    dp[i]=math.min(dp[i],dp[i-2]+math.abs(h[i]-h[i-2]))
end
print(dp[n])

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 30 40 20

Sample Output 1

30

If we follow the path 1 → 2 → 4, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

2
10 10

Sample Output 2

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 3

6
30 10 60 10 60 50

Sample Output 3

40

If we follow the path 1 → 3 → 5 → 6, the total cost incurred would be |30 - 60| + |60 - 60| + |60 - 50| = 40.


n=io.read"*n"
h={}for i=1,n do
h[i]=io.read"*n"end

dp={0,math.abs(h[1]-h[2])}

for i=3,n do
dp[i]=math.min(dp[i-2]+math.abs(h[i-2]-h[i]),dp[i-1]+math.abs(h[i-1]-h[i]))
end
print(dp[n])


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
----
local function array(n, default_val)
    local metatables = {}
    if default_val ~= nil then
        metatables[1] = {__index = function() return default_val end}
    end
    for i=2,n do
        metatables[i] = {__index = function(parent, k)
            local child = setmetatable({}, metatables[i-1])
            rawset(parent, k, child)
            return child
        end}
    end
    return setmetatable({}, metatables[n])
end
----
local N = read.n()
local h = read.N(N)
local function diff(i, j)
    if j > N then
        return 10^9
    end
    return math.abs(h[i] - h[j])
end
local tbl = array(1, 10^9)
tbl[1] = 0
for i=1,N-1 do
    tbl[i+1] = math.min(tbl[i+1], diff(i,i+1) + tbl[i])
    tbl[i+2] = math.min(tbl[i+2], diff(i,i+2) + tbl[i])
end
print(tbl[N])


local n = io.read("*n")
local t, r = {}, {}
for i = 1, n do
  t[i] = io.read("*n")
  r[i] = 0
end
local abs, min = math.abs, math.min
r[2] = abs(t[2] - t[1])
for i = 3, n do
  r[i] = min(r[i - 1] + abs(t[i] - t[i - 1]), r[i - 2] + abs(t[i] - t[i - 2]))
end
print(r[n])


n=tonumber(io.read())
str=io.read()
h={}
for w in string.gmatch(str,"[^ ]+")do
	table.insert(h,w)
end
memo={}
function cal(i)
	if(memo[i]~=nil) then
		return memo[i]
	end
	local way1=cal(i-1)+math.abs(h[i]-h[i-1])
	local way2=99999999
	if(i>2) then
		way2=cal(i-2)+math.abs(h[i]-h[i-2])
	end
	if(way1<way2) then
		memo[i]=way1
	else
		memo[i]=way2
	end
	return memo[i]
end
memo[1]=0
memo[2]=math.abs(h[2]-h[1])
print(math.floor(cal(n)))


n=tonumber(io.read())
str=io.read()
h={}
for w in string.gmatch(str,"[^ ]+")do
	table.insert(h,w)
end
memo={}
function cal(i)
	if(memo[i]~=nil) then
		return memo[i]
	end
	local way1=cal(i-1)+math.abs(h[i]-h[i-1])
	local way2=99999999
	if(i>2) then
		way2=cal(i-2)+math.abs(h[i]-h[i-2])
	end
	if(way1<way2) then
		memo[i]=way1
	else
		memo[i]=way2
	end
	return memo[i]
end
memo[1]=0
memo[2]=math.abs(h[2]-h[1])
print(cal(n))


local n,k=io.read("n","n")
local h={}
for i=1,n do
    h[i]=io.read("n")
end

local INF=10^20
local dp={0}
for i=2,n do
    dp[i]=INF
end

for i=1,n do
    for j=1,k do
        if i+j<=n then
            dp[i+j]=math.min(dp[i+j],dp[i]+math.abs(h[i]-h[i+j]))
        end
    end
end
print(dp[n])

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 100

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

5 3
10 30 40 50 20

Sample Output 1

30

If we follow the path 1 → 2 → 5, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

3 1
10 20 10

Sample Output 2

20

If we follow the path 1 → 2 → 3, the total cost incurred would be |10 - 20| + |20 - 10| = 20.

Sample Input 3

2 100
10 10

Sample Output 3

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 4

10 4
40 10 20 70 80 10 20 70 80 60

Sample Output 4

40

If we follow the path 1 → 4 → 8 → 10, the total cost incurred would be |40 - 70| + |70 - 70| + |70 - 60| = 40.


local n,k=io.read("n","n")
local h={}
for i=1,n do
    h[i]=io.read("n")
end

local INF=math.maxinteger
local dp={0}
for i=2,n do
    dp[i]=INF
end

for i=1,n do
    for j=1,k do
        if i+j<=n then
            dp[i+j]=math.min(dp[i+j],dp[i]+math.abs(h[i]-h[i+j]))
        end
    end
end
print(dp[n])


local mmi, mma = math.min, math.max
local mab = math.abs
local n, k = io.read("*n", "*n")
local h = {}
local cost = {}
for i = 1, n do
  h[i] = io.read("*n")
  cost[i] = 1000000007 * 100
end
cost[1] = 0
for i = 1, n - 1 do
  local lim = mmi(k, n - i)
  for j = 1, lim do
    cost[i + j] = mmi(cost[i + j], cost[i] + mab(h[i + j] - h[i]))
  end
end
print(cost[n])


n=io.read"*n"
k=io.read"*n"
h={}for i=1,n do
h[i]=io.read"*n"end

dp={0}
for i=2,n do
dp[i]=math.huge
for j=1,math.min(i-1,k) do
dp[i]=math.min(dp[i-j]+math.abs(h[i]-h[i-j]),dp[i])
end
end
print(dp[n])


n=io.read"*n"
k=io.read"*n"
h={}for i=1,n do
h[i]=io.read"*n"end

dp={0}
for i=2,n do
for j=1,math.min(i-1,k) do
dp[i]=math.min(dp[i-j]+math.abs(h[i]-h[i-j]),dp[i]or math.huge)
end
end
print(dp[n])


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
----
local function array(n, default_val)
    local metatables = {}
    if default_val ~= nil then
        metatables[1] = {__index = function() return default_val end}
    end
    for i=2,n do
        metatables[i] = {__index = function(parent, k)
            local child = setmetatable({}, metatables[i-1])
            rawset(parent, k, child)
            return child
        end}
    end
    return setmetatable({}, metatables[n])
end
----
local N, K = read.nn()
local h = read.N(N)
local function diff(i, j)
    if j > N then
        return 10^20
    end
    return math.abs(h[i] - h[j])
end
local tbl = array(1, 10^20)
tbl[1] = 0
for i=1,N-1 do
    for k=1,K do
        tbl[i+k] = math.min(tbl[i+k], diff(i,i+k) + tbl[i])
    end
end
print(tbl[N])


local n, k = io.read("*n", "*n")
local t, r = {}, {}
for i = 1, n do
  t[i] = io.read("*n")
  r[i] = 0
end
local abs, min = math.abs, math.min
r[2] = abs(t[2] - t[1])
for i = 2, n do
  r[i] = r[i - 1] + abs(t[i] - t[i - 1])
  for j = 2, k do
    if i <= j then break end
    r[i] = min(r[i], r[i - j] + abs(t[i] - t[i - j]))
  end
end
print(r[n])


str1=io.read()
str2=io.read()
info={}
h={}
for w in string.gmatch(str1,"[^ ]+")do
	table.insert(info,w)
end
for w in string.gmatch(str2,"[^ ]+")do
	table.insert(h,w)
end
memo={}
memo[1]=0
function cal(i,n,k)
	if(memo[i]~=nil)then
		return memo[i]
	end
	local list={}
	local min=999999999
	for j=i-1,i-k,-1 do
		if(j<1)then
			do
				break
			end
		end
		list[j]=cal(j,n,k)+math.abs(h[i]-h[j])
		if(list[j]<min)then
			min=list[j]
		end
	end
	if(min~=999999999)then
		memo[i]=min
	end
	return min
end
local a={}
print(math.floor(cal(tonumber(info[1]),tonumber(info[1]),tonumber(info[2]))))


local n,m=io.read("n","n")
local w,v={},{}
for i=1,n do
    w[i],v[i]=io.read("n","n")
end

local dp={}
for i=1,n+1 do
    dp[i]={}
    for j=0,m do
        dp[i][j]=0
    end
end

for i=1,n do
    for j=0,m do
        if j-w[i]>=0 then
            dp[i+1][j]=math.max(dp[i+1][j],dp[i][j-w[i]]+v[i])
        end
        dp[i+1][j]=math.max(dp[i+1][j],dp[i][j])
    end
end

print(string.format("%d",dp[n+1][m]))

Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^5

1 \leq w_i \leq W

1 \leq v_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

5 5
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 2

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


local ffi=require"ffi"
ffi.cdef[[
int scanf(const char*,...);
int printf(const char*,...);
]]
local C=ffi.C

local function max(a,b)return a<b and b or a end

N=io.read"*n"
W=io.read"*n"
w,v={},{}for i=1,N do
w[i]=io.read"*n"
v[i]=io.read"*n"end

dp=ffi.new("int64_t[101][100001]")
for i=0,W do dp[0][i]=0 end

for i=1,N do
dp[i]={}
for j=0,W do
if(j<w[i])then dp[i][j]=dp[i-1][j]
else dp[i][j]=max(dp[i-1][j-w[i]]+v[i],dp[i-1][j])end
end
end
C.printf("%ld\n",dp[N][W])


local ffi=require"ffi"
ffi.cdef[[
int scanf(const char*,...);
int printf(const char*,...);
]]
local C=ffi.C

local function max(a,b)return a<b and b or a end

N=io.read"*n"
W=io.read"*n"
w,v={},{}for i=1,N do
w[i]=io.read"*n"
v[i]=io.read"*n"end

dp=ffi.new("int64_t[100][100000]")
for i=0,W do dp[0][i]=0 end

for i=1,N do
dp[i]={}
for j=0,W do
if(j<w[i])then dp[i][j]=dp[i-1][j]
else dp[i][j]=max(dp[i-1][j-w[i]]+v[i],dp[i-1][j])end
end
end
C.printf("%ld\n",dp[N][W])


local ffi=require"ffi"
ffi.cdef[[
int scanf(const char*,...);
int printf(const char*,...);
]]
local C=ffi.C

local function max(a,b)return a<b and b or a end

N=io.read"*n"
W=io.read"*n"
w,v={},{}for i=1,N do
w[i]=io.read"*n"
v[i]=io.read"*n"end

dp=ffi.new("int64_t[100][100]")
for i=0,W do dp[0][i]=0 end

for i=1,N do
dp[i]={}
for j=0,W do
if(j<w[i])then dp[i][j]=dp[i-1][j]
else dp[i][j]=max(dp[i-1][j-w[i]]+v[i],dp[i-1][j])end
end
end
C.printf("%ld\n",dp[N][W])


local ffi=require"ffi"
N=io.read"*n"
W=io.read"*n"
w,v={},{}for i=1,N do
w[i]=io.read"*n"
v[i]=io.read"*n"end

dp={[0]={}}
for i=0,W do dp[0][i]=0 end

for i=1,N do
dp[i]={}
for j=0,W do
if(j<w[i])then dp[i][j]=dp[i-1][j]
else dp[i][j]=math.max(dp[i-1][j-w[i]]+v[i],dp[i-1][j])end
end
end
print(dp[N][W])


N=io.read"*n"
W=io.read"*n"
w,v={},{}for i=1,N do
w[i]=io.read"*n"
v[i]=io.read"*n"end

dp={[0]={}}
for i=0,W do dp[0][i]=0 end

for i=1,N do
dp[i]={}
for j=0,W do
if(j<w[i])then dp[i][j]=dp[i-1][j]
else dp[i][j]=math.max(dp[i-1][j-w[i]]+v[i],dp[i-1][j])end
end
end
print(dp[N][W])


N=io.read"*n"
W=io.read"*n"
w,v={},{}for i=1,N do
w[i]=io.read"*n"
v[i]=io.read"*n"end

dp={[0]={}}
for i=0,W do dp[0][i]=0 end

for i=1,N do
dp[i]={}
for j=0,W do
if(j<w[i])then dp[i][j]=dp[i-1][j]
else dp[i][j]=math.max(dp[i-1][j-w[i]]+v[i],dp[i-1][j])end
end
end
for i=0,N do print(table.concat(dp[i],"\t"))end
print(dp[N][W])