local mfl, mce = math.floor, math.ceil
local mmi, mma = math.min, math.max
local bls, brs = bit.lshift, bit.rshift
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    local cnt = bls(1, i - 1)
    for j = 1, cnt 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, n, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.stage = {{}}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.stage[stagenum] = {}
  end
  self.stagenum = stagenum
  self.left_stage = {}
  for i = 1, n do
    local sp, sz = 1, bls(1, stagenum - 1)
    while(i - 1) % sz ~= 0 do
      sp, sz = sp + 1, brs(sz, 1)
    end
    self.left_stage[i] = sp
  end
  self.sz_stage = {}
  local tmp, sp = 1, stagenum
  for i = 1, n do
    if tmp * 2 == i then tmp, sp = tmp * 2, sp - 1 end
    self.sz_stage[i] = sp
  end
  for i = 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 stagenum = self.stagenum
  local ret = self.emptyvalue
  while left <= right do
    local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    local sz = bls(1, stagenum - stage)
    ret = self.func(ret, self.stage[stage][1 + brs(left - 1, stagenum - stage)])
    left = left + sz
  end
  return ret
end
SegTree.update = function(self, idx)
  for i = self.stagenum - 1, 1, -1 do
    local dst = brs(idx + 1, 1)
    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
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = mma(self.stage[self.stagenum][idx], value)
  if not silent then
    self:update(idx)
  end
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local n, k = io.read("*n", "*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
local z = 300000
local st = SegTree.new(z + 1, mma, 0)
for i = 1, n do
  local ai = a[i]
  local left = mma(0, ai - k)
  local right = mmi(z, ai + k)
  local cur = st:getRange(left + 1, right + 1)
  st:setValue(ai + 1, cur + 1)
end
print(st.stage[1][1])

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

Score : 400 points

Problem Statement

You are given a sequence A_1, A_2, ..., A_N and an integer K.

Print the maximum possible length of a sequence B that satisfies the following conditions:

B is a (not necessarily continuous) subsequence of A.

For each pair of adjacents elements of B, the absolute difference of the elements is at most K.

Constraints

1 \leq N \leq 300,000

0 \leq A_i \leq 300,000

0 \leq K \leq 300,000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1
A_2
:
A_N

Output

Print the answer.

Sample Input 1

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

Sample Output 1

7

For example, B = (1, 4, 3, 6, 9, 7, 4) satisfies the conditions.

It is a subsequence of A = (1, 5, 4, 3, 8, 6, 9, 7, 2, 4).

All of the absolute differences between two adjacent elements (|1-4|, |4-3|, |3-6|, |6-9|, |9-7|, |7-4|) are at most K = 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.


local mfl, mce = math.floor, math.ceil
local mmi, mma = math.min, math.max
local bls, brs = bit.lshift, bit.rshift
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    local cnt = bls(1, i - 1)
    for j = 1, cnt 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, n, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.stage = {{}}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.stage[stagenum] = {}
  end
  self.stagenum = stagenum
  self.left_stage = {}
  for i = 1, n do
    local sp, sz = 1, bls(1, stagenum - 1)
    while(i - 1) % sz ~= 0 do
      sp, sz = sp + 1, brs(sz, 1)
    end
    self.left_stage[i] = sp
  end
  self.sz_stage = {}
  local tmp, sp = 1, stagenum
  for i = 1, n do
    if tmp * 2 == i then tmp, sp = tmp * 2, sp - 1 end
    self.sz_stage[i] = sp
  end
  for i = 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 stagenum = self.stagenum
  local ret = self.emptyvalue
  while left <= right do
    local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    local sz = bls(1, stagenum - stage)
    ret = self.func(ret, self.stage[stage][1 + brs(left - 1, stagenum - stage)])
    left = left + sz
  end
  return ret
end
SegTree.update = function(self, idx)
  for i = self.stagenum - 1, 1, -1 do
    local dst = brs(idx + 1, 1)
    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
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = value
  if not silent then
    self:update(idx)
  end
end
SegTree.right_bound = function(self, left, right)
  local retpos = left - 1
  local l, r = left, right
  local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
  local stagenum = self.stagenum
  while true do
    local sz = bls(1, stagenum - stage)
    if not self.stage[stage][mce(l / sz)] then
      retpos = l + sz - 1
      if retpos == right then break end
      if l + sz <= r then
        l = l + sz
        stage = mma(self.left_stage[l], self.sz_stage[r - l + 1])
      else break end
    else
      if sz ~= 1 then stage, r = stage + 1, l + sz - 2
      else break end
    end
  end
  return retpos + 1
end
SegTree.left_bound = function(self, left, right)
  local retpos = right + 1
  local stage, l, r = 1, left, right
  local stagenum = self.stagenum
  while true do
    local sz = bls(1, stagenum - stage)
    while r % sz ~= 0 or r + 1 - l < sz do
      stage = stage + 1
      sz = bls(1, stagenum - stage)
    end
    if not self.stage[stage][mfl(r / sz)] then
      retpos = r - sz + 1
      if l + sz <= r then stage, l, r = 1, l, r - sz
      else break end
    else
      if sz ~= 1 then stage, l, r = stage + 1, r - sz + 2, r
      else break end
    end
  end
  return retpos - 1
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local n = io.read("*n")
local xs, ys = {}, {}
local xidx, yidx = {}, {}
local parent = {}
for i = 1, n do
  xidx[i], yidx[i] = 0, 0
  parent[i] = i
end

local function uf_findroot(idx)
  local idx_update = idx
  while parent[idx] ~= idx do
    idx = parent[idx]
  end
  while parent[idx_update] ~= idx do
    parent[idx_update], idx_update = idx, parent[idx_update]
  end
  return idx
end

for i = 1, n do
  xs[i], ys[i] = io.read("*n", "*n")
  xidx[xs[i]] = i
  yidx[ys[i]] = i
end
local function orfunc(a, b) return a or b end
local st1 = SegTree.new(n, orfunc, false)
for i = 1, n do
  local src = xidx[i]
  local v = st1:left_bound(1, ys[src])
  while 1 <= v do
    local dst = yidx[v]
    local rs, rd = uf_findroot(src), uf_findroot(dst)
    parent[rd], parent[dst] = rs, rs
    st1:setValue(v, false)
    if v == 1 then break end
    v = st1:left_bound(1, v - 1)
  end
  st1:setValue(ys[src], true)
end

local group = {}
for i = 1, n do
  group[i] = 0
end
for i = 1, n do
  local r = uf_findroot(i)
  group[r] = group[r] + 1
end
for i = 1, n do
  local r = uf_findroot(i)
  print(group[r])
end

Score : 300 points

Problem Statement

There are N cities on a 2D plane. The coordinate of the i-th city is (x_i, y_i). Here (x_1, x_2, \dots, x_N) and (y_1, y_2, \dots, y_N) are both permuations of (1, 2, \dots, N).

For each k = 1,2,\dots,N, find the answer to the following question:

Rng is in City k.
Rng can perform the following move arbitrarily many times:

move to another city that has a smaller x-coordinate and a smaller y-coordinate, or a larger x-coordinate and a larger y-coordinate, than the city he is currently in.

How many cities (including City k) are reachable from City k?

Constraints

1 \leq N \leq 200,000

(x_1, x_2, \dots, x_N) is a permutation of (1, 2, \dots, N).

(y_1, y_2, \dots, y_N) is a permutation of (1, 2, \dots, N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print N lines. In i-th line print the answer to the question when k = i.

Sample Input 1

4
1 4
2 3
3 1
4 2

Sample Output 1

1
1
2
2

Rng can reach City 4 from City 3, or conversely City 3 from City 4.

Sample Input 2

7
6 4
4 3
3 5
7 1
2 7
5 2
1 6

Sample Output 2

3
3
1
1
2
3
2


local mfl, mce = math.floor, math.ceil
local mmi, mma = math.min, math.max
local bls, brs = bit.lshift, bit.rshift
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    local cnt = bls(1, i - 1)
    for j = 1, cnt 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, n, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.stage = {{}}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.stage[stagenum] = {}
  end
  self.stagenum = stagenum
  self.left_stage = {}
  for i = 1, n do
    local sp, sz = 1, bls(1, stagenum - 1)
    while(i - 1) % sz ~= 0 do
      sp, sz = sp + 1, brs(sz, 1)
    end
    self.left_stage[i] = sp
  end
  self.sz_stage = {}
  local tmp, sp = 1, stagenum
  for i = 1, n do
    if tmp * 2 == i then tmp, sp = tmp * 2, sp - 1 end
    self.sz_stage[i] = sp
  end
  for i = 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 stagenum = self.stagenum
  local ret = self.emptyvalue
  while left <= right do
    local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    local sz = bls(1, stagenum - stage)
    ret = self.func(ret, self.stage[stage][1 + brs(left - 1, stagenum - stage)])
    left = left + sz
  end
  return ret
end
SegTree.update = function(self, idx)
  for i = self.stagenum - 1, 1, -1 do
    local dst = brs(idx + 1, 1)
    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
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = value
  if not silent then
    self:update(idx)
  end
end
SegTree.right_bound = function(self, left, right)
  local retpos = left - 1
  local l, r = left, right
  local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
  local stagenum = self.stagenum
  while true do
    local sz = bls(1, stagenum - stage)
    if not self.stage[stage][mce(l / sz)] then
      retpos = l + sz - 1
      if retpos == right then break end
      if l + sz <= r then
        l = l + sz
        stage = mma(self.left_stage[l], self.sz_stage[r - l + 1])
      else break end
    else
      if sz ~= 1 then stage, r = stage + 1, l + sz - 2
      else break end
    end
  end
  return retpos + 1
end
SegTree.left_bound = function(self, left, right)
  local retpos = right + 1
  local stage, l, r = 1, left, right
  local stagenum = self.stagenum
  while true do
    local sz = bls(1, stagenum - stage)
    while r % sz ~= 0 or r + 1 - l < sz do
      stage = stage + 1
      sz = bls(1, stagenum - stage)
    end
    if not self.stage[stage][mfl(r / sz)] then
      retpos = r - sz + 1
      if l + sz <= r then stage, l, r = 1, l, r - sz
      else break end
    else
      if sz ~= 1 then stage, l, r = stage + 1, r - sz + 2, r
      else break end
    end
  end
  return retpos - 1
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local n = io.read("*n")
local xs, ys = {}, {}
local xidx, yidx = {}, {}
local parent = {}
for i = 1, n do
  xidx[i], yidx[i] = 0, 0
  parent[i] = i
end

local function uf_findroot(idx)
  local idx_update = idx
  while parent[idx] ~= idx do
    idx = parent[idx]
  end
  while parent[idx_update] ~= idx do
    parent[idx_update], idx_update = idx, parent[idx_update]
  end
  return idx
end

for i = 1, n do
  xs[i], ys[i] = io.read("*n", "*n")
  xidx[xs[i]] = i
  yidx[ys[i]] = i
end
local function orfunc(a, b) return a or b end
local st1 = SegTree.new(n, orfunc, false)
for i = 1, n do
  local src = xidx[i]
  local v = st1:left_bound(1, ys[src])
  if 1 <= v then
    local dst = yidx[v]
    local rs, rd = uf_findroot(src), uf_findroot(dst)
    parent[rd], parent[dst] = rs, rs
  end
  st1:setValue(ys[src], true)
end
local st2 = SegTree.new(n, orfunc, false)
for i = n, 1, -1 do
  local src = xidx[i]
  local v = st2:right_bound(ys[src], n)
  if v <= n then
    local dst = yidx[v]
    local rs, rd = uf_findroot(src), uf_findroot(dst)
    parent[rd], parent[dst] = rs, rs
  end
  st2:setValue(ys[src], true)
end
local group = {}
for i = 1, n do
  group[i] = 0
end
for i = 1, n do
  local r = uf_findroot(i)
  group[r] = group[r] + 1
end
for i = 1, n do
  local r = uf_findroot(i)
  print(group[r])
end


local bls, brs = bit.lshift, bit.rshift
local bxor = bit.bxor
local mce, mfl, msq, mmi, mma, mab = math.ceil, math.floor, math.sqrt, math.min, math.max, math.abs

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

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

local n = io.read()
n = lltonumber(n)
n = 2LL * n
local lim = 31622777
local function getprimes(x)
  local primes = {}
  local allnums = {}
  for i = 1, x do allnums[i] = true end
  for i = 2, x do
    if allnums[i] then
      table.insert(primes, i)
      local lim = mfl(x / i)
      for j = 2, lim do
        allnums[j * i] = false
      end
    end
  end
  return primes
end
-- print(os.clock())
local primes = getprimes(lim)
-- print(os.clock())
local function getdivisorparts(x, primes, lim)
  local prime_num = #primes
  local tmp = {}
  local raw = {}
  local primepos = 1
  local dv = primes[primepos]
  while primepos <= prime_num and dv <= lim do
    if x % dv == 0LL then
      local p = dv
      x = x / dv
      while x % dv == 0 do
        x = x / dv
        p = p * dv
      end
      table.insert(tmp, p)
      table.insert(raw, dv)
      -- lim = mce(msq(x))
    end
    if primepos == prime_num then break end
    primepos = primepos + 1
    dv = primes[primepos]
  end
  if x ~= 1LL then
    table.insert(tmp, x)
    table.insert(raw, x)
  end
  return tmp, raw
end
-- for i = 1, #dvs do
--   print(dvs[i])-- maybe LL
-- end

local function grayCode(x)
  return bxor(x, brs(x, 1))
end

-- add_func(idx), rm_func(idx), work_func()
local function grayWalk(size, add_func, rm_func, work_func)
  local prv = 0
  local total = bls(1, size) - 1
  local bpos = {}
  for i = 1, size do
    bpos[bls(1, i - 1)] = i
  end
  -- if need first work then use below
  -- work_func()
  for i = 1, total do
    local v = grayCode(i)
    if prv < v then
      prv, v = v, v - prv
      add_func(bpos[v])
    else
      prv, v = v, prv - v
      rm_func(bpos[v])
    end
    work_func()
  end
end

local dvs, raw = getdivisorparts(n, primes, lim)
local tot = bls(1, #dvs)
local left_use = {}
local minfact = n
local kcand = 1
local left = 1LL

local function solve(a, b, x, y)
  if b == 0LL then
    x[1] = 1LL
    y[1] = 0LL
    return a
  end
  local d = solve(b, a % b, y, x)
  y[1] = y[1] - (a / b) * x[1]
  return d
end

local function add_func(idx)
  left_use[tostring(raw[idx])] = true
  left = left * dvs[idx]
end
local function rm_func(idx)
  left_use[tostring(raw[idx])] = false
  left = left / dvs[idx]
end
local x, y = {0}, {0}
local function work_func()
  local right = n / left
  solve(left, right, x, y)
  x[1] = -x[1]
  while x[1] < 0LL do
    x[1] = x[1] + right
  end
  local z = x[1] * left
  if 0LL < z and z < minfact then
  -- if x[1] * left < minfact then
    minfact = left * x[1]
    -- print(x[1], left, minfact)
  end
end
grayWalk(#dvs, add_func, rm_func, work_func)
local ans = minfact
ans = tostring(ans):gsub("LL", "")
print(ans)

Score : 600 points

Problem Statement

Given is an integer N.
Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N.
It can be proved that such a positive integer k always exists.

Constraints

1 \leq N \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer in a line.

Sample Input 1

11

Sample Output 1

10

1+2+\cdots+10=55 holds and 55 is indeed a multple of N=11.
There are no positive integers k \leq 9 that satisfy the condition, so the answer is k = 10.

Sample Input 2

20200920

Sample Output 2

1100144


-- Vicfred
-- https://atcoder.jp/contests/abc179/tasks/abc179_b
-- simulation
n = io.read("*n")

b = {}
d = {}
for i = 1, n do b[i], d[i] = io.read("*n", "*n") end

flag = false

for i = 1, n-3 do
   if b[i] == d[i] and
       b[i + 1] == d[i + 1] and
       b[i + 2] == d[i + 2] then
       flag = true
   end
end

if flag then
    print("Yes")
else
    print("No")
end

Score : 200 points

Problem Statement

Tak performed the following action N times: rolling two dice.
The result of the i-th roll is D_{i,1} and D_{i,2}.

Check if doublets occurred at least three times in a row.
Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.

Constraints

3 \leq N \leq 100

1\leq D_{i,j} \leq 6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
D_{1,1} D_{1,2}
\vdots
D_{N,1} D_{N,2}

Output

Print Yes if doublets occurred at least three times in a row. Print No otherwise.

Sample Input 1

5
1 2
6 6
4 4
3 3
3 2

Sample Output 1

Yes

From the second roll to the fourth roll, three doublets occurred in a row.

Sample Input 2

5
1 1
2 2
3 4
5 5
6 6

Sample Output 2

No

Sample Input 3

6
1 1
2 2
3 3
4 4
5 5
6 6

Sample Output 3

Yes


local mmi, mma = math.min, math.max
local mod = 998244353
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 n, k = io.read("*n", "*n")
local ls, rs = {}, {}
for i = 1, k do
  ls[i], rs[i] = io.read("*n", "*n")
end
local t = {1}
local imos = {0}
for i = 2, n + 1 do
  t[i] = 0
  imos[i] = 0
end
for src = 1, n do
  if 1 < src then
    imos[src] = badd(imos[src], imos[src - 1])
    t[src] = imos[src]
  end
  if src < n then
    for j = 1, k do
      local dstmin = src + ls[j]
      local dstmax = mmi(n, src + rs[j])
      if dstmin <= dstmax then
        imos[dstmin] = badd(imos[dstmin], t[src])
        imos[dstmax + 1] = bsub(imos[dstmax + 1], t[src])
      end
    end
  end
end
print(t[n])

Score : 400 points

Problem Statement

There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.

Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.

You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K].
Let S be the union of these K segments.
Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.

When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.

To help Tak, find the number of ways to go to Cell N, modulo 998244353.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq K \leq \min(N, 10)

1 \leq L_i \leq R_i \leq N

[L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
L_1 R_1
L_2 R_2
:
L_K R_K

Output

Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.

Sample Input 1

5 2
1 1
3 4

Sample Output 1

4

The set S is the union of the segment [1, 1] and the segment [3, 4], therefore S = \{ 1, 3, 4 \} holds.

There are 4 possible ways to get to Cell 5:

1 \to 2 \to 3 \to 4 \to 5,

1 \to 2 \to 5,

1 \to 4 \to 5 and

1 \to 5.

Sample Input 2

5 2
3 3
5 5

Sample Output 2

0

Because S = \{ 3, 5 \} holds, you cannot reach to Cell 5.
Print 0.

Sample Input 3

5 1
1 2

Sample Output 3

5

Sample Input 4

60 3
5 8
1 3
10 15

Sample Output 4

221823067

Note that you have to print the answer modulo 998244353.


local mfl, mce = math.floor, math.ceil
local mmi, mma = math.min, math.max
local bls, brs = bit.lshift, bit.rshift
local LazyRangeSeg = {}
LazyRangeSeg.create = function(self, n, func)
  local stagenum, mul = 1, 1
  self.func = func
  self.n = n
  self.stage = {{n}}
  self.lazy = {{n}}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.stage[stagenum] = {}
    self.lazy[stagenum] = {}
    for i = 1, mul do
      self.stage[stagenum][i] = n
      self.lazy[stagenum][i] = n
    end
  end
  self.left_stage = {}
  for i = 1, n do
    local sp, sz = 1, bls(1, stagenum - 1)
    while(i - 1) % sz ~= 0 do
      sp, sz = sp + 1, brs(sz, 1)
    end
    self.left_stage[i] = sp
  end
  self.sz_stage = {}
  local tmp, sp = 1, stagenum
  for i = 1, n do
    if tmp * 2 == i then tmp, sp = tmp * 2, sp - 1 end
    self.sz_stage[i] = sp
  end
  self.stagenum = stagenum
end
LazyRangeSeg.resolve = function(self, right)
  local stagenum = self.stagenum
  local offset = 0
  for i = 1, stagenum - 1 do
    local p = offset + bls(1, stagenum - i)
    if p < right then
      offset = p
      p = p + bls(1, stagenum - i)
    end
    if right < p then
      local curidx = brs(p, stagenum - i)
      local incval = self.lazy[i][curidx]
      if incval < self.n then
        self:resolveRange(i + 1, curidx * 2 - 1, incval, true)
        self:resolveRange(i + 1, curidx * 2, incval, true)
        self.lazy[i + 1][curidx * 2 - 1] = self.func(self.lazy[i + 1][curidx * 2 - 1], incval)
        self.lazy[i + 1][curidx * 2] = self.func(self.lazy[i + 1][curidx * 2], incval)
        self.lazy[i][curidx] = self.n
      end
    elseif p == right then
      break
    else
      assert(false)
    end
  end
end
LazyRangeSeg.resolveRange = function(self, stagepos, idx, value, shallow)
  self.stage[stagepos][idx] = self.func(self.stage[stagepos][idx], value)
  if shallow then return end
  for i = stagepos - 1, 1, -1 do
    local dst = brs(idx + 1, 1)
    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
LazyRangeSeg.getRange = function(self, left, right)
  if 1 < left then self:resolve(left - 1) end
  self:resolve(right)
  local stagenum = self.stagenum
  local ret = self.n
  while left <= right do
    local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    local sz = bls(1, stagenum - stage)
    ret = self.func(ret, self.stage[stage][1 + brs(left - 1, stagenum - stage)])
    left = left + sz
  end
  return ret
end
LazyRangeSeg.setRange = function(self, left, right, value)
  if 1 < left then self:resolve(left - 1) end
  self:resolve(right)
  local stagenum = self.stagenum
  while left <= right do
    local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    local sz = bls(1, stagenum - stage)
    local len = right - left + 1
    local idx = 1 + brs(left - 1, stagenum - stage)
    self:resolveRange(stage, idx, value)
    self.lazy[stage][idx] = self.func(self.lazy[stage][idx], value)
    left = left + sz
  end
end
LazyRangeSeg.new = function(n, func)
  local obj = {}
  setmetatable(obj, {__index = LazyRangeSeg})
  obj:create(n, func)
  return obj
end

local n, q = io.read("*n", "*n")
local st_v = LazyRangeSeg.new(n, mmi)
local st_h = LazyRangeSeg.new(n, mmi)
local tot = 0
for iq = 1, q do
  local tp, x = io.read("*n", "*n")
  if tp == 1 then
    local white_row = st_v:getRange(x, x)
    tot = tot + white_row - 2
    if 2 < white_row then
      st_h:setRange(2, white_row - 1, x)
    end
  else
    local white_col = st_h:getRange(x, x)
    tot = tot + white_col - 2
    if 2 < white_col then
      st_v:setRange(2, white_col - 1, x)
    end
  end
end
print((n - 2) * (n - 2) - tot)

Score : 600 points

Problem Statement

There is a grid with N rows and N columns of squares. Let (i, j) be the square at the i-th row from the top and the j-th column from the left.

Each of the central (N-2) \times (N-2) squares in the grid has a black stone on it.
Each of the 2N - 1 squares on the bottom side and the right side has a white stone on it.

Q queries are given. We ask you to process them in order.
There are two kinds of queries. Their input format and description are as follows:

1 x: Place a white stone on (1, x). After that, for each black stone between (1, x) and the first white stone you hit if you go down from (1, x), replace it with a white stone.

2 x: Place a white stone on (x, 1). After that, for each black stone between (x, 1) and the first white stone you hit if you go right from (x, 1), replace it with a white stone.

How many black stones are there on the grid after processing all Q queries?

Constraints

3 \leq N \leq 2\times 10^5

0 \leq Q \leq \min(2N-4,2\times 10^5)

2 \leq x \leq N-1

Queries are pairwise distinct.

Input

Input is given from Standard Input in the following format:

N Q
Query_1
\vdots
Query_Q

Output

Print how many black stones there are on the grid after processing all Q queries.

Sample Input 1

5 5
1 3
2 3
1 4
2 2
1 2

Sample Output 1

1

After each query, the grid changes in the following way:

Sample Input 2

200000 0

Sample Output 2

39999200004

Sample Input 3

176527 15
1 81279
2 22308
2 133061
1 80744
2 44603
1 170938
2 139754
2 15220
1 172794
1 159290
2 156968
1 56426
2 77429
1 97459
2 71282

Sample Output 3

31159505795


local x = io.read("n")

print(x == 0 and 1 or 0)

Score : 100 points

Problem Statement

Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.

Constraints

0 \leq x \leq 1

x is an integer

Input

Input is given from Standard Input in the following format:

x

Output

Print 1 if x is equal to 0, or 0 if x is equal to 1.

Sample Input 1

1

Sample Output 1

0

Sample Input 2

0

Sample Output 2

1


local max = math.max
local n_t = {}
for i = 1, 4 do
	n_t[i] = io.read("n")
end

print(max(n_t[1]*n_t[3], n_t[1]*n_t[4], n_t[2]*n_t[3], n_t[2]*n_t[4]))

Score : 200 points

Problem Statement

Given are integers a,b,c and d.
If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?

Constraints

-10^9 \leq a \leq b \leq 10^9

-10^9 \leq c \leq d \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

Print the answer.

Sample Input 1

1 2 1 1

Sample Output 1

2

If x = 1 and y = 1 then x \times y = 1.
If x = 2 and y = 1 then x \times y = 2.
Therefore, the answer is 2.

Sample Input 2

3 5 -4 -2

Sample Output 2

-6

The answer can be negative.

Sample Input 3

-1000000000 0 -1000000000 0

Sample Output 3

1000000000000000000


local n = io.read("n")

--nC1 * (n - 1)C1 10^(n - 2)

if n == 1 then
	print(0)
	os.exit()
end

local ten_pow, nin_pow = 1, 0
local eig_pow_t, nin_pow_t = {8}, {9}
for i = 2, n do
	eig_pow_t[i] = (eig_pow_t[i - 1] * 8) % 1000000007
	nin_pow_t[i] = (nin_pow_t[i - 1] * 9) % 1000000007
end

for i = 1, n do
	ten_pow = (ten_pow * 10) % 1000000007
end
print(ten_pow)
for i = 1, n do
	print(eig_pow_t[i - 1], nin_pow_t[n - i])
	local num = nin_pow + ((eig_pow_t[i - 1] or 1) * (nin_pow_t[n - i] or 1)) % 1000000007
	nin_pow = num % 1000000007
end
print(nin_pow)
print(eig_pow_t[n])
local out = ((nin_pow * 2) % 1000000007 + eig_pow_t[n]) % 1000000007
out = out < 0 and out + 1000000007 or out
out = ten_pow - out < 0 and ten_pow - out + 1000000007 or ten_pow - out
print(out)

Score : 300 points

Problem Statement

How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?

0 \leq A_i \leq 9

There exists some i such that A_i=0 holds.

There exists some i such that A_i=9 holds.

The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^9 + 7.

Sample Input 1

2

Sample Output 1

2

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

Sample Input 2

1

Sample Output 2

0

Sample Input 3

869121

Sample Output 3

2511445


local n=io.read("n")
local maxz=0
local minz=10^10
local maxw=0
local minw=10^10
for i=1,n do
    local x,y=io.read("n","n")
    maxz=math.max(maxz,x+y)
    minz=math.min(minz,x+y)
    maxw=math.max(maxw,x-y)
    minw=math.min(minw,x-y)
end
print(math.max(maxz-minz,maxw-minw))

Score : 500 points

Problem Statement

There are N points on the 2D plane, i-th of which is located on (x_i, y_i).
There can be multiple points that share the same coordinate.
What is the maximum possible Manhattan distance between two distinct points?

Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-y_j|.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq x_i,y_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the answer.

Sample Input 1

3
1 1
2 4
3 2

Sample Output 1

4

The Manhattan distance between the first point and the second point is |1-2|+|1-4|=4, which is maximum possible.

Sample Input 2

2
1 1
1 1

Sample Output 2

0


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

local function uf_findroot(idx)
  local idx_update = idx
  while parent[idx] ~= idx do
    idx = parent[idx]
  end
  while parent[idx_update] ~= idx do
    parent[idx_update], idx_update = idx, parent[idx_update]
  end
  return idx
end

for i = 1, q do
  local t, u, v = io.read("*n", "*n", "*n")
  local ru, rv = uf_findroot(u), uf_findroot(v)
  if t == 0 then
    parent[rv], parent[v] = ru, ru
  else
    print(ru == rv and 1 or 0)
  end
end

Score : 100 points

Problem Statement

You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.

0 u v: Add an edge (u, v).

1 u v: Print 1 if u and v are in the same connected component, 0 otherwise.

Constraints

1 \leq N \leq 200,000

1 \leq Q \leq 200,000

0 \leq u_i, v_i \lt N

Input

Input is given from Standard Input in the following format:

N Q
t_1 u_1 v_1
t_2 u_2 v_2
:
t_Q u_Q v_Q

出力

For each query of the latter type, print the answer.

Sample Input 1

4 7
1 0 1
0 0 1
0 2 3
1 0 1
1 1 2
0 0 2
1 1 3

Sample Output 1

0
1
0
1


-- Hopcroft-Karp
HKmatch = {}

HKmatch.create = function(self, an, bn)
  self.dst = {}
  self.edge = {}
  for i = 1, an do
    self.dst[i] = false
    self.edge[i] = {}
  end
  self.src = {}
  self.invcnt = {}
  self.invs = {}
  self.invpos = {}
  self.padded = {}
  for i = 1, bn do
    self.src[i] = false
    self.invs[i] = {}
  end
  self.p = {}
  self.tasks = {}
  self.level = {}
end

HKmatch.addEdge = function(self, a, b)
  table.insert(self.edge[a], b)
  if not self.dst[a] and not self.src[b] then
    self.dst[a] = b
    self.src[b] = a
  end
end

HKmatch.makeAugPath = function(self)
  local tasknum = 0
  local tasks = self.tasks
  local level = self.level
  local edge = self.edge
  local src = self.src
  local an = #self.dst
  local bn = #src
  local invcnt, invs = self.invcnt, self.invs
  local p, psize = self.p, 0
  local padded = self.padded
  local lvinf = an + 1
  for i = 1, an do
    if self.dst[i] then
      level[i] = lvinf
    else
      tasknum = tasknum + 1
      tasks[tasknum] = i
      level[i] = 1
    end
  end
  for i = 1, bn do
    invcnt[i] = 0
    padded[i] = false
  end
  local done = 0
  local lvmax = lvinf
  while done < tasknum do
    done = done + 1
    local a = tasks[done]
    if lvmax < level[a] then break end
    for i = 1, #edge[a] do
      local b = edge[a][i]
      local sb = src[b]
      if sb then
        if level[sb] == lvinf then
          tasknum = tasknum + 1
          tasks[tasknum] = sb
          level[sb] = level[a] + 1
          invcnt[b] = invcnt[b] + 1
          invs[b][invcnt[b]] = a
        elseif level[sb] == level[a] + 1 then
          invcnt[b] = invcnt[b] + 1
          invs[b][invcnt[b]] = a
        end
      else
        if lvmax == lvinf then
          lvmax = level[a]
        end
        if padded[b] then
        else
          padded[b] = true
          psize = psize + 1
          p[psize] = b
        end
        invcnt[b] = invcnt[b] + 1
        invs[b][invcnt[b]] = a
      end
    end
  end
  self.psize = psize
  return lvmax
end

HKmatch.dfs = function(self, b, lv)
  for i = 1, self.invcnt[b] do
    local a = self.invs[b][i]
    if self.level[a] == 1 or (self.level[a] == lv and self:dfs(self.dst[a], lv - 1)) then
      self.dst[a], self.src[b] = b, a
      self.level[a] = -1
      return true
    end
  end
end

HKmatch.restore = function(self, bend, lvend)
  local invs, invcnt, invpos = self.invs, self.invcnt, self.invpos
  local dst, src = self.dst, self.src
  local level = self.level
  local bn = #src
  for i = 1, bn do
    invpos[i] = 0
  end
  local accept = false
  local tasks = self.tasks
  local taskpos = 1
  tasks[1] = bend
  while 0 < taskpos do
    local b = tasks[taskpos]
    if accept then
      local a = invs[b][invpos[b]]
      dst[a], src[b] = b, a
      level[a] = -1
      taskpos = taskpos - 1
    else
      if invpos[b] == invcnt[b] then
        taskpos = taskpos - 1
      else
        local ip = invpos[b] + 1
        invpos[b] = ip
        local a = invs[b][ip]
        if level[a] == 1 then
          accept = true
          dst[a], src[b] = b, a
          level[a] = -1
          taskpos = taskpos - 1
        elseif level[a] + taskpos == lvend + 1 then
          taskpos = taskpos + 1
          tasks[taskpos] = dst[a]
        end
        -- if self.level[a] == 1 or (self.level[a] == lv and self:dfs(self.dst[a], lv - 1)) then
        --   self.dst[a], self.src[b] = b, a
        --   self.level[a] = -1
        --   return true
        -- end
      end
    end
  end
end

HKmatch.matching = function(self)
  local an = #self.dst
  local lv = self:makeAugPath()
  while lv <= an do
    for i = 1, self.psize do
      self:restore(self.p[i], lv)
      -- self:dfs(self.p[i], lv)
    end
    lv = self:makeAugPath()
  end
end

HKmatch.new = function(an, bn)
  local obj = {}
  setmetatable(obj, {__index = HKmatch})
  obj:create(an, bn)
  return obj
end

local h, w = io.read("*n", "*n", "*l")
local an, bn = 0, 0
local as, bs = {}, {}
local invidx = {}
for i = 1, h do
  for j = 1, w do
    local idx = (i - 1) * w + j
    if (i + j) % 2 == 0 then
      an = an + 1
      as[an] = idx
      invidx[idx] = an
    else
      bn = bn + 1
      bs[bn] = idx
      invidx[idx] = bn
    end
  end
end
local hkm = HKmatch.new(an, bn)
local map = {}
for i = 1, h do
  local s = io.read()
  for j = 1, w do
    local idx = (i - 1) * w + j
    map[idx] = s:sub(j, j)
  end
end
for i = 1, h - 1 do
  for j = 1, w do
    local idx = (i - 1) * w + j
    local isleft = (i + j) % 2 == 0
    if map[idx] == "." and map[idx + w] == "." then
      if isleft then
        hkm:addEdge(invidx[idx], invidx[idx + w])
      else
        hkm:addEdge(invidx[idx + w], invidx[idx])
      end
    end
  end
end
for i = 1, h do
  for j = 1, w - 1 do
    local idx = (i - 1) * w + j
    local isleft = (i + j) % 2 == 0
    if map[idx] == "." and map[idx + 1] == "." then
      if isleft then
        hkm:addEdge(invidx[idx], invidx[idx + 1])
      else
        hkm:addEdge(invidx[idx + 1], invidx[idx])
      end
    end
  end
end
hkm:matching()
local cnt = 0
for i = 1, an do
  local d = hkm.dst[i]
  if d then
    cnt = cnt + 1
    local l, r = as[i], bs[d]
    if l + w == r then
      map[l] = "v"
      map[r] = "^"
    elseif l - w == r then
      map[r] = "v"
      map[l] = "^"
    elseif l + 1 == r then
      map[l] = ">"
      map[r] = "<"
    elseif l - 1 == r then
      map[l] = "<"
      map[r] = ">"
    end
  end
end
print(cnt)
for i = 1, h do
  for j = 1, w do
    io.write(map[(i - 1) * w + j])
  end
  io.write("\n")
end

Score : 100 points

Problem Statement

You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j).
Some of the squares contain an object. All the remaining squares are empty.
The state of the grid is represented by strings S_1,S_2,\cdots,S_N. The square (i,j) contains an object if S_{i,j}= # and is empty if S_{i,j}= ..

Consider placing 1 \times 2 tiles on the grid. Tiles can be placed vertically or horizontally to cover two adjacent empty squares.
Tiles must not stick out of the grid, and no two different tiles may intersect. Tiles cannot occupy the square with an object.

Calculate the maximum number of tiles that can be placed and any configulation that acheives the maximum.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

S_i is a string with length M consists of # and ..

Input

Input is given from Standard Input in the following format:

N M
S_1
S_2
\vdots
S_N

Output

On the first line, print the maximum number of tiles that can be placed.

On the next N lines, print a configulation that achieves the maximum.
Precisely, output the strings t_1,t_2,\cdots,t_N constructed by the following way.

t_i is initialized to S_i.

For each (i,j), if there is a tile that occupies (i,j) and (i+1,j), change t_{i,j}:=v, t_{i+1,j}:=^.

For each (i,j), if there is a tile that occupies (i,j) and (i,j+1), change t_{i,j}:=>, t_{i,j+1}:=<.

See samples for further information.

You may print any configulation that maximizes the number of tiles.

Sample Input 1

3 3
#..
..#
...

Sample Output 1

3
#><
vv#
^^.

The following output is also treated as a correct answer.

3
#><
v.#
^><


local mmi, mma = math.min, math.max
local MinCostFlow = {}

MinCostFlow.initialize = function(self, n, spos, tpos, inf)
  self.n = n
  self.spos, self.tpos = spos, tpos
  self.inf = inf
  -- edge_dst[src][i] := dst
  self.edge_dst = {}
  -- edge_cost[src][i] := cost from src to edge_dst[src][i]
  self.edge_cost = {}
  -- edge_cap[src][i] := capacity from src to edge_dst[src][i]
  self.edge_cap = {}
  -- initial capacity. corresponding to edge_cap
  self.edge_initialcap = {}
  -- edge_dst_invedge_idx[src][i] := "j" where edge_dst[dst][j] == src
  -- in this case, edge_dst_invedge_idx[dst][j] should be "i".
  self.edge_dst_invedge_idx = {}
  -- len[v] := length from spos. len[spos] := 0
  self.len = {}
  -- sub_graph_flag[v] := whether to contains the vertex v in the sub-graph or not
  self.sub_graph_flag = {}
  -- sub_graph_v[i] := list of vertexes that are contained in the sub-graph. from tpos to spos.
  self.sub_graph_v = {}
  -- sub_graph_edgeidx[i] := edge index from sub_graph_v[i + 1] to sub_graph_v[i]
  self.sub_graph_edgeidx = {}
  -- sub_graph_size := the size of sub_graph_v.
  -- may not equal to #sub_graph_v (because not cleared).
  self.sub_graph_size = 0
  for i = 1, n do
    self.edge_dst[i] = {}
    self.edge_cost[i] = {}
    self.edge_cap[i] = {}
    self.edge_initialcap[i] = {}
    self.edge_dst_invedge_idx[i] = {}
    self.len[i] = 0
    self.sub_graph_flag[i] = false
  end
end

MinCostFlow.addEdge = function(self, src, dst, cost, cap)
  table.insert(self.edge_dst[src], dst)
  table.insert(self.edge_cost[src], cost)
  table.insert(self.edge_cap[src], cap)
  table.insert(self.edge_initialcap[src], cap)
  table.insert(self.edge_dst_invedge_idx[src], 1 + #self.edge_dst[dst])
  table.insert(self.edge_dst[dst], src)
  table.insert(self.edge_cost[dst], -cost)
  table.insert(self.edge_cap[dst], 0)--invcap
  table.insert(self.edge_initialcap[dst], 0)--invcap
  table.insert(self.edge_dst_invedge_idx[dst], #self.edge_dst[src])
end
MinCostFlow.invwalk_recursive = function(self, invsrc)
  if invsrc == self.spos then return true end
  for i = 1, #self.edge_dst[invsrc] do
    local invdst = self.edge_dst[invsrc][i]
    local j = self.edge_dst_invedge_idx[invsrc][i]
    if 0 < self.edge_cap[invdst][j]
    and self.len[invdst] + self.edge_cost[invdst][j] == self.len[invsrc]
    and not self.sub_graph_flag[invdst] then
      self.sub_graph_size = self.sub_graph_size + 1
      self.sub_graph_v[self.sub_graph_size] = invdst
      self.sub_graph_edgeidx[self.sub_graph_size - 1] = j
      self.sub_graph_flag[invdst] = true

      if self:invwalk_recursive(invdst) then
        return true
      else
        -- self.sub_graph_flag[invdst] = false
        self.sub_graph_size = self.sub_graph_size - 1
      end
    end
  end
  return false
end

MinCostFlow.makeSubGraph = function(self)
  local inf = self.inf
  local len = self.len
  local n = self.n
  local edge_dst, edge_cap = self.edge_dst, self.edge_cap
  local edge_dst_invedge_idx = self.edge_dst_invedge_idx
  local edge_cost = self.edge_cost
  local sub_graph_v = self.sub_graph_v
  local sub_graph_edgeidx = self.sub_graph_edgeidx
  local sub_graph_flag = self.sub_graph_flag
  for i = 1, self.n do
    len[i] = inf
    sub_graph_flag[i] = false
  end
  -- Bellman-Ford
  local updated1, updated2 = {}, {}
  for i = 1, n do
    updated1[i] = true
  end
  len[self.spos] = 0
  for irp = 1, n do
    local updsrc = irp % 2 == 1 and updated1 or updated2
    local upddst = irp % 2 == 1 and updated2 or updated1
    for i = 1, n do
      upddst[i] = false
    end
    for src = 1, n do
      if updsrc[src] then
        local eddst, edcap, edcost = edge_dst[src], edge_cap[src], edge_cost[src]
        for i = 1, #eddst do
          if 0 < edcap[i] then
            local dst = eddst[i]
            local cost = edcost[i]
            if len[src] + cost < len[dst] then
              len[dst] = len[src] + cost
              upddst[dst] = true
            end
          end
        end
      end
    end
  end
  self.sub_graph_size = 0
  if inf <= len[self.tpos] then
    return 0
  end
  -- restore route (from tpos to spos)
  self.sub_graph_size = 1
  sub_graph_v[1] = self.tpos
  self:invwalk_recursive(self.tpos)
  local min_capacity = inf
  for i = self.sub_graph_size, 2, -1 do
    local src = sub_graph_v[i]
    local j = sub_graph_edgeidx[i - 1]
    min_capacity = mmi(min_capacity, edge_cap[src][j])
  end
  return min_capacity
end

MinCostFlow.flow = function(self, capacity)
  local edge_dst, edge_cap = self.edge_dst, self.edge_cap
  local edge_dst_invedge_idx = self.edge_dst_invedge_idx
  local sub_graph_v = self.sub_graph_v
  local sub_graph_edgeidx = self.sub_graph_edgeidx
  for i = self.sub_graph_size, 2, -1 do
    local src = sub_graph_v[i]
    local dst = sub_graph_v[i - 1]
    local j = sub_graph_edgeidx[i - 1]
    edge_cap[src][j] = edge_cap[src][j] - capacity
    local k = edge_dst_invedge_idx[src][j]
    edge_cap[dst][k] = edge_cap[dst][k] + capacity
  end
end

MinCostFlow.getMinCostFlow = function(self, amount, invalid)
  local ret = 0
  local cap = self:makeSubGraph()
  while 0 < cap do
    cap = mmi(amount, cap)
    ret = ret + self.len[self.tpos] * cap
    self:flow(cap)
    amount = amount - cap
    if 0 < amount then
      cap = self:makeSubGraph()
    else
      break
    end
  end
  if 0 < amount then return invalid end
  return ret
end

local n, k = io.read("*n", "*n")
local sp, tp = 2 * n + 1, 2 * n + 2
MinCostFlow:initialize(tp, sp, tp, 1000000007 * 1000)
for i = 1, n do
  MinCostFlow:addEdge(sp, i, 0, k)
  MinCostFlow:addEdge(n + i, tp, 0, k)
end
MinCostFlow:addEdge(n * 2 + 1, n * 2 + 2, 0, n * k)
for i = 1, n do
  for j = 1, n do
    local a = io.read("*n")
    MinCostFlow:addEdge(i, n + j, -a, 1)
  end
end
local amount = -MinCostFlow:getMinCostFlow(n * k)
amount = math.abs(amount) -- "-0" to "0"
print(amount)
local used = {}
for i = 1, n * n do used[i] = false end
for row = 1, n do
  local edge = MinCostFlow.edge_dst[row]
  local cap = MinCostFlow.edge_cap[row]
  local initcap = MinCostFlow.edge_initialcap[row]
  for j = 1, #edge do
    local col = edge[j] - n
    if cap[j] < initcap[j] then
      used[(row - 1) * n + col] = true
    end
  end
end
for i = 1, n do
  for j = 1, n do
    io.write(used[(i - 1) * n + j] and "X" or ".")
  end
  io.write("\n")
end

Score : 100 points

Problem Statement

You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j).
A nonnegative integer A_{i,j} is written for each square (i,j).

You choose some of the squares so that each row and column contains at most K chosen squares.
Under this constraint, calculate the maximum value of the sum of the integers written on the chosen squares.
Additionally, calculate a way to choose squares that acheives the maximum.

Constraints

1 \leq N \leq 50

1 \leq K \leq N

0 \leq A_{i,j} \leq 10^9

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N K
A_{1,1} A_{1,2} \cdots A_{1,N}
A_{2,1} A_{2,2} \cdots A_{2,N}
\vdots
A_{N,1} A_{N,2} \cdots A_{N,N}

Output

On the first line, print the maximum value of the sum of the integers written on the chosen squares.

On the next N lines, print a way that achieves the maximum.

Precisely, output the strings t_1,t_2,\cdots,t_N, that satisfies t_{i,j}=X if you choose (i,j) and t_{i,j}=. otherwise.

You may print any way to choose squares that maximizes the sum.

Sample Input 1

3 1
5 3 2
1 4 8
7 6 9

Sample Output 1

19
X..
..X
.X.

Sample Input 2

3 2
10 10 1
10 10 1
1 1 10

Sample Output 2

50
XX.
XX.
..X


local mfl = math.floor
local TranFFT = {}

TranFFT.initialize = function(self)
  self.size = 20
  self.n = 1048576
  self.mod = 998244353
  self.w = 646
  self.ninv = 998243401
  self.winv = 208611436
  self.p2 = {1}
  for i = 2, self.size do
    self.p2[i] = self.p2[i - 1] * 2
  end
  self.binv = {}
  for i = 1, self.n do
    local y, z = 0, i - 1
    for j = 1, self.size do
      y = y + (z % 2) * self.p2[self.size + 1 - j]
      z = mfl(z / 2)
    end
    self.binv[i] = y + 1
  end
  self.wmul = {1}
  for i = 2, self.n do
    self.wmul[i] = self:mul(self.wmul[i - 1], self.w)
  end
  self.winvmul = {1}
  for i = 2, self.n do
    self.winvmul[i] = self:mul(self.winvmul[i - 1], self.winv)
  end
end

TranFFT.mul = function(self, 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) % self.mod
end

TranFFT.add = function(self, x, y) return (x + y) % self.mod end

TranFFT.fft_common = function(self, ary, wmul)
  local ret = {}
  for i = 1, self.n do
    ret[i] = ary[self.binv[i]]
  end
  for i = 1, self.size do
    local step_size = self.p2[i]
    local step_count = self.p2[self.size + 1 - i]
    for istep = 1, step_count do
      local ofst = (istep - 1) * step_size * 2
      for j = 1, step_size do
        local a1, a2 = ret[ofst + j], ret[ofst + step_size + j]
        ret[ofst + j] = self:add(a1, self:mul(a2, wmul[1 + (j - 1) * step_count]))
        ret[ofst + step_size + j] = self:add(a1, self:mul(a2, wmul[1 + (j + step_size - 1) * step_count]))
      end
    end
  end
  return ret
end

TranFFT.fft = function(self, ary)
  return self:fft_common(ary, self.wmul)
end
TranFFT.ifft = function(self, ary)
  local ret = self:fft_common(ary, self.winvmul)
  for i = 1, self.n do
    ret[i] = self:mul(ret[i], self.ninv)
  end
  return ret
end

-- sample (ATC001-C)
TranFFT:initialize()
local a, b = {}, {}
local n, m = io.read("*n", "*n")
for i = 1, TranFFT.n do
  a[i] = 0
  b[i] = 0
end
for i = 1, n do
  a[i] = io.read("*n")
end
for i = 1, m do
  b[i] = io.read("*n")
end

local at = TranFFT:fft(a)
local bt = TranFFT:fft(b)
for i = 1, TranFFT.n do
  at[i] = TranFFT:mul(at[i], bt[i])
end
local c = TranFFT:ifft(at)
for i = 1, n + m - 1 do
  io.write(c[i])
  io.write(i == n + m - 1 and "\n" or " ")
end

Score : 100 points

Problem Statement

You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353.

Constraints

1 \leq N, M \leq 524288

0 \leq a_i, b_i < 998244353

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N M
a_0 a_1 ... a_{N-1}
b_0 b_1 ... b_{M-1}

Output

Print the answer in the following format:

c_0 c_1 ... c_{(N - 1) + (M - 1)}

Sample Input 1

4 5
1 2 3 4
5 6 7 8 9

Sample Output 1

5 16 34 60 70 70 59 36

Sample Input 2

1 1
10000000
10000000

Sample Output 2

871938225


-- Strongly Connected Component Decomposition
local n, m = io.read("*n", "*n")
local edge = {}
local edge_asked = {}
local invedge = {}
local invedge_asked = {}
for i = 1, n do
  edge[i] = {}
  edge_asked[i] = 0
  invedge[i] = {}
  invedge_asked[i] = 0
end
local edgeinfo = {}
for i = 1, m do
  local a, b = io.read("*n", "*n")
  a, b = a + 1, b + 1
  edgeinfo[i] = {a, b}
  table.insert(edge[a], b)
  table.insert(invedge[b], a)
end

local asked = {}
local sccd_root = {}
for i = 1, n do
  asked[i] = false
  sccd_root[i] = 0
end

local function SCCD_dfs(spos, dfs_way)
  local tasks = {spos}
  while 0 < #tasks do
    local src = tasks[#tasks]
    asked[src] = true
    table.remove(tasks)
    if edge_asked[src] == #edge[src] then
      table.insert(dfs_way, src)
    else
      table.insert(tasks, src)
      edge_asked[src] = edge_asked[src] + 1
      local dst = edge[src][edge_asked[src]]
      if not asked[dst] then
        table.insert(tasks, dst)
      end
    end
  end
end

local function SCCD_invdfs(spos, rootid)
  local tasks = {spos}
  while 0 < #tasks do
    local src = tasks[#tasks]
    sccd_root[src] = rootid
    table.remove(tasks)
    while invedge_asked[src] < #invedge[src] do
      invedge_asked[src] = invedge_asked[src] + 1
      local dst = invedge[src][invedge_asked[src]]
      if asked[dst] and sccd_root[dst] == 0 then
        table.insert(tasks, src)
        table.insert(tasks, dst)
        break
      end
    end
  end
end

local function SCCD_make()
  for src = 1, n do
    if not asked[src] then
      local dfs_way = {}
      SCCD_dfs(src, dfs_way)
      for i = #dfs_way, 1, -1 do
        local src = dfs_way[i]
        if sccd_root[src] == 0 then
          SCCD_invdfs(src, src)
        end
      end
    end
  end
end

SCCD_make()

local gsize = {}
local gedge, ginvedge = {}, {}
local glen = {}
local gmember = {}
for i = 1, n do
  gsize[i] = 0
  gedge[i], ginvedge[i] = {}, {}
  glen[i] = 0
  gmember[i] = {}
end
for i = 1, n do
  local r = sccd_root[i]
  gsize[r] = gsize[r] + 1
  table.insert(gmember[r], i)
end
for i = 1, m do
  local a, b = edgeinfo[i][1], edgeinfo[i][2]
  local ra, rb = sccd_root[a], sccd_root[b]
  if ra ~= rb then
    table.insert(gedge[ra], rb)
    table.insert(ginvedge[rb], ra)
  end
end
local topo_tasks = {}
local topo_asked_cnt = {}
local retcnt = 0
for i = 1, n do
  topo_asked_cnt[i] = 0
  if 0 < gsize[i] then retcnt = retcnt + 1 end
  if 0 < gsize[i] and #ginvedge[i] == 0 then
    table.insert(topo_tasks, i)
  end
end
print(retcnt)
local topo_done = 0
while topo_done < #topo_tasks do
  topo_done = topo_done + 1
  local g = topo_tasks[topo_done]
  io.write(#gmember[g])
  for i = 1, #gmember[g] do
    io.write(" " .. gmember[g][i] - 1)
  end
  io.write("\n")
  for i = 1, #gedge[g] do
    local dst = gedge[g][i]
    topo_asked_cnt[dst] = topo_asked_cnt[dst] + 1
    if topo_asked_cnt[dst] == #ginvedge[dst] then
      table.insert(topo_tasks, dst)
    end
  end
end

Score : 100 points

Problem Statement

You are given a directed graph with N vertices and M edges, not necessarily simple. The i-th edge is oriented from the vertex a_i to the vertex b_i.
Divide this graph into strongly connected components and print them in their topological order.

Constraints

1 \leq N \leq 500,000

1 \leq M \leq 500,000

0 \leq a_i, b_i < N

Input

Input is given from Standard Input in the following format:

N M
a_0 b_0
a_1 b_1
:
a_{M - 1} b_{M - 1}

Output

Print 1+K lines, where K is the number of strongly connected components.
Print K on the first line.
Print the information of each strongly connected component in next K lines in the following format, where l is the number of vertices in the strongly connected component and v_i is the index of the vertex in it.

l v_0 v_1 ... v_{l-1}

Here, for each edge (a_i, b_i), b_i should not appear in earlier line than a_i.

If there are multiple correct output, print any of them.

Sample Input 1

6 7
1 4
5 2
3 0
5 5
4 1
0 3
4 2

Sample Output 1

4
1 5
2 4 1
1 2
2 3 0


local mfl, mce = math.floor, math.ceil
local mmi, mma = math.min, math.max
local bls, brs = bit.lshift, bit.rshift
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    local cnt = bls(1, i - 1)
    for j = 1, cnt 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, n, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.stage = {{}}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.stage[stagenum] = {}
  end
  self.stagenum = stagenum
  self.left_stage = {}
  for i = 1, n do
    local sp, sz = 1, bls(1, stagenum - 1)
    while(i - 1) % sz ~= 0 do
      sp, sz = sp + 1, brs(sz, 1)
    end
    self.left_stage[i] = sp
  end
  self.sz_stage = {}
  local tmp, sp = 1, stagenum
  for i = 1, n do
    if tmp * 2 == i then tmp, sp = tmp * 2, sp - 1 end
    self.sz_stage[i] = sp
  end
  for i = 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 stagenum = self.stagenum
  local ret = self.emptyvalue
  while left <= right do
    local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    local sz = bls(1, stagenum - stage)
    ret = self.func(ret, self.stage[stage][1 + brs(left - 1, stagenum - stage)])
    left = left + sz
  end
  return ret
end
SegTree.update = function(self, idx)
  for i = self.stagenum - 1, 1, -1 do
    local dst = brs(idx + 1, 1)
    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
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = value
  if not silent then
    self:update(idx)
  end
end

SegTree.right_bound = function(self, val, left, right)
  local ret, retpos = self.emptyvalue, left - 1
  local l, r = left, right
  local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
  local stagenum = self.stagenum
  while true do
    local sz = bls(1, stagenum - stage)
    local tmp = self.func(ret, self.stage[stage][mce(l / sz)])
    if tmp < val then
      ret, retpos = tmp, l + sz - 1
      if retpos == right then break end
      if l + sz <= r then
        l = l + sz
        stage = mma(self.left_stage[l], self.sz_stage[r - l + 1])
      else break end
    else
      if sz ~= 1 then stage, r = stage + 1, l + sz - 2
      else break end
    end
  end
  return retpos + 1
end

SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local n, q = io.read("*n", "*n")
local st = SegTree.new(n, mma, -1)
for i = 1, n do
  local a = io.read("*n")
  st:setValue(i, a, true)
end
st:updateAll()
for iq = 1, q do
  local a, b, c = io.read("*n", "*n", "*n")
  if a == 1 then
    st:setValue(b, c)
  elseif a == 2 then
    print(st:getRange(b, c))
  else
    print(st:right_bound(c, b, n))
  end
end

Score : 100 points

Problem Statement

You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.

The type of i-th query is represented by T_i.

T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.

T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.

T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.

Constraints

1 \leq N \leq 2 \times 10^5

0 \leq A_i \leq 10^9

1 \leq Q \leq 2 \times 10^5

1 \leq T_i \leq 3

1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)

1 \leq L_i \leq R_i \leq N (T_i=2)

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query

Each query is given in the following format:

If T_i=1,3,

T_i X_i V_i

If T_i=2,

T_i L_i R_i

Output

For each query with T_i=2, 3, print the answer.

Sample Input 1

5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3

Sample Output 1

3
3
2
6

First query: Print 3, which is the maximum of (A_1,A_2,A_3,A_4,A_5)=(1,2,3,2,1).

Second query: Since 3>A_2, j=2 does not satisfy the condition．Since 3 \leq A_3, print j=3.

Third query: Replace the value of A_3 with 1. It becomes A=(1,2,1,2,1).

Fourth query: Print 2, which is the maximum of (A_2,A_3,A_4)=(2,1,2).

Fifth query: Since there is no j that satisfies the condition, print j=N+1=6.


local mfl, mce = math.floor, math.ceil
local mmi, mma = math.min, math.max
local bls, brs = bit.lshift, bit.rshift
local LazyRangeSeg = {}
LazyRangeSeg.create = function(self, n)
  local stagenum, mul = 1, 1
  self.n0, self.n1 = {{0}}, {{0}}
  self.c01, self.c10 = {{0}}, {{0}}
  self.lazy = {{false}}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.n0[stagenum], self.n1[stagenum] = {}, {}
    self.c01[stagenum], self.c10[stagenum] = {}, {}
    self.lazy[stagenum] = {}
    for i = 1, mul do
      self.n0[stagenum][i], self.n1[stagenum][i] = 0, 0
      self.c01[stagenum][i], self.c10[stagenum][i] = 0, 0
      self.lazy[stagenum][i] = false
    end
  end
  self.left_stage = {}
  for i = 1, n do
    local sp, sz = 1, bls(1, stagenum - 1)
    while(i - 1) % sz ~= 0 do
      sp, sz = sp + 1, brs(sz, 1)
    end
    self.left_stage[i] = sp
  end
  self.sz_stage = {}
  local tmp, sp = 1, stagenum
  for i = 1, n do
    if tmp * 2 == i then tmp, sp = tmp * 2, sp - 1 end
    self.sz_stage[i] = sp
  end
  self.stagenum = stagenum
end
LazyRangeSeg.resolve = function(self, right)
  local stagenum = self.stagenum
  local offset = 0
  for i = 1, stagenum - 1 do
    local p = offset + bls(1, stagenum - i)
    if p < right then
      offset = p
      p = p + bls(1, stagenum - i)
    end
    if right < p then
      local curidx = brs(p, stagenum - i)
      if self.lazy[i][curidx] then
        self:resolveRange(i + 1, curidx * 2 - 1, true)
        self:resolveRange(i + 1, curidx * 2, incval, true)
        self.lazy[i + 1][curidx * 2 - 1] = not self.lazy[i + 1][curidx * 2 - 1]
        self.lazy[i + 1][curidx * 2] = not self.lazy[i + 1][curidx * 2]
        self.lazy[i][curidx] = false
      end
    elseif p == right then
      break
    else
      assert(false)
    end
  end
end
local function merge(ln0, ln1, lc01, lc10, rn0, rn1, rc01, rc10)
  return ln0 + rn0, ln1 + rn1, lc01 + rc01 + ln0 * rn1, lc10 + rc10 + ln1 * rn0
end
LazyRangeSeg.resolveRange = function(self, stagepos, idx, shallow)
  self.n0[stagepos][idx], self.n1[stagepos][idx] = self.n1[stagepos][idx], self.n0[stagepos][idx]
  self.c01[stagepos][idx], self.c10[stagepos][idx] = self.c10[stagepos][idx], self.c01[stagepos][idx]
  if shallow then return end
  for i = stagepos - 1, 1, -1 do
    local dst = brs(idx + 1, 1)
    local rem = dst * 4 - 1 - idx
    if rem < idx then rem, idx = idx, rem end
    self.n0[i][dst], self.n1[i][dst], self.c01[i][dst], self.c10[i][dst]
    = merge(self.n0[i + 1][idx], self.n1[i + 1][idx],
            self.c01[i + 1][idx], self.c10[i + 1][idx],
            self.n0[i + 1][rem], self.n1[i + 1][rem],
            self.c01[i + 1][rem], self.c10[i + 1][rem])
    idx = dst
  end
end
LazyRangeSeg.getRange = function(self, left, right)
  if 1 < left then self:resolve(left - 1) end
  self:resolve(right)
  local stagenum = self.stagenum
  local n0, n1, c01, c10 = 0, 0, 0, 0
  while left <= right do
    local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    local sz = bls(1, stagenum - stage)
    local pos = 1 + brs(left - 1, stagenum - stage)
    n0, n1, c01, c10
    = merge(n0, n1, c01, c10, self.n0[stage][pos], self.n1[stage][pos], self.c01[stage][pos], self.c10[stage][pos])
    left = left + sz
  end
  return c10
end
LazyRangeSeg.setRange = function(self, left, right)
  if 1 < left then self:resolve(left - 1) end
  self:resolve(right)
  local stagenum = self.stagenum
  while left <= right do
    local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    local sz = bls(1, stagenum - stage)
    local len = right - left + 1
    local idx = 1 + brs(left - 1, stagenum - stage)
    self:resolveRange(stage, idx)
    self.lazy[stage][idx] = not self.lazy[stage][idx]
    left = left + sz
  end
end
LazyRangeSeg.setAll = function(self, s)
  local n = brs(#s + 1, 1)
  local stagenum = self.stagenum
  for i = 1, n do
    local b = s:byte(i * 2 - 1)
    if b == 48 then
      self.n0[stagenum][i] = 1
    else
      self.n1[stagenum][i] = 1
    end
  end
  for i = stagenum - 1, 1, -1 do
    local cnt = bls(1, i - 1)
    for j = 1, cnt do
      self.n0[i][j], self.n1[i][j], self.c01[i][j], self.c10[i][j]
      = merge(self.n0[i + 1][j * 2 - 1], self.n1[i + 1][j * 2 - 1],
              self.c01[i + 1][j * 2 - 1], self.c10[i + 1][j * 2 - 1],
              self.n0[i + 1][j * 2], self.n1[i + 1][j * 2],
              self.c01[i + 1][j * 2], self.c10[i + 1][j * 2])
    end
  end
end
LazyRangeSeg.new = function(n)
  local obj = {}
  setmetatable(obj, {__index = LazyRangeSeg})
  obj:create(n)
  return obj
end

local n, q = io.read("*n", "*n", "*l")
local lzst = LazyRangeSeg.new(n)
lzst:setAll(io.read())
for iq = 1, q do
-- while true do
  local t, l, r = io.read("*n", "*n", "*n")
  -- if t == 0 then break end
  if t == 1 then
    lzst:setRange(l, r)
  else
    print(lzst:getRange(l, r))
  end
end

Score : 100 points

Problem Statement

You are given a binary array A=(A_1,A_2,\cdots,A_N) of length N.

Process Q queries of the following types. The i-th query is represented by three integers T_i,L_i,R_i.

T_i=1: Replace the value of A_j with 1-A_j for each L_i \leq j \leq R_i.

T_i=2: Calculate the inversion(*) of the array A_{L_i},A_{L_i+1},\cdots,A_{R_i}．

Note：The inversion of the array x_1,x_2,\cdots,x_k is the number of the pair of integers i,j with 1 \leq i < j \leq k, x_i > x_j.

Constraints

1 \leq N \leq 2 \times 10^5

0 \leq A_i \leq 1

1 \leq Q \leq 2 \times 10^5

1 \leq T_i \leq 2

1 \leq L_i \leq R_i \leq N

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N Q
A_1 A_2 \cdots A_N
T_1 L_1 R_1
T_2 L_2 R_2
\vdots
T_Q L_Q R_Q

Output

For each query with T_i=2, print the answer.

Sample Input 1

5 5
0 1 0 0 1
2 1 5
1 3 4
2 2 5
1 1 3
2 1 2

Sample Output 1

2
0
1

First query: Print 2, which is the inversion of (A_1,A_2,A_3,A_4,A_5)=(0,1,0,0,1).

Second query: Replace the value of A_3 and A_4 with 1 and 1, respectively.

Third query: Print 0, which is the inversion of (A_2,A_3,A_4,A_5)=(1,1,1,1).

Fourth query: Replace the value of A_1, A_2 and A_4 with 1, 0 and 0, respectively.

Fifth query: Print 1, which is the inversion of (A_1,A_2)=(1,0).


-- Atcoder https://atcoder.jp/contests/abc177/tasks/abc177_a

local input= io.read()
local d, t, s = string.match(input, "(%d+) (%d+)")

if t * s >= d then
    print("yes")
else
    print("no")
end

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes 20 minutes to go 2000 meters to the place at a speed of 100 meters per minute. They have planned to meet in 20 minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


local a = io.read("*n")
b, c = io.read("*n", "*n")
print(a <= b * c and "Yes" or "No")


local max = math.max
local min = math.min
--[[ https://www.slideshare.net/iwiwi/ss-3578491 3~18of73 ]]--

--半分の実装のみ(これでも十分早いらしい)
local UFT = {}

---要素数nでpar[]を初期化
function UFT.new(n)
	local obj = {par = {}}
	for i = 1, n do
		obj.par[i] = i
	end
	return setmetatable(obj,{__index = UFT})
end

---木の根を求める
function UFT:find(x)
	if self.par[x] == x then
		-- 根
		return x
	else
		-- 経路圧縮
		self.par[x] = self:find(self.par[x])
		return self.par[x]
	end
end

---xとyが同じ集合に属するか否か
function UFT:same(x, y)
	return self:find(x) == self:find(y)
end

---xとyの属する集合を併合
function UFT:union(x, y)
	x = self:find(x)
	y = self:find(y)
	if x == y then
		return
	end

	self.par[max(x, y)] = min(x, y)
end

--[[ I referred until here. ]]--

local read = io.read

local n, m = read("n", "n")
local uft = UFT.new(n)
for i = 1, m do
	local a_i, b_i = read("n", "n")
	uft:union(a_i, b_i)
end

local is_finded_num_t = {}
for i = 1, n do
	local par_num = uft.par[i]
	if is_finded_num_t[par_num] then
		is_finded_num_t[par_num] = is_finded_num_t[par_num] + 1
	else
		is_finded_num_t[par_num] = 1
	end
end

local uft_par_max = -1
for i = 1, n do
	if is_finded_num_t[i] then
		uft_par_max = max(uft_par_max, is_finded_num_t[i])
	end
end

print(uft_par_max)

Score : 400 points

Problem Statement

There are N persons called Person 1 through Person N.

You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.

If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.

Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.

At least how many groups does he need to make?

Constraints

2 \leq N \leq 2\times 10^5

0 \leq M \leq 2\times 10^5

1\leq A_i,B_i\leq N

A_i \neq B_i

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
\vdots
A_M B_M

Output

Print the answer.

Sample Input 1

5 3
1 2
3 4
5 1

Sample Output 1

3

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

Sample Input 2

4 10
1 2
2 1
1 2
2 1
1 2
1 3
1 4
2 3
2 4
3 4

Sample Output 2

4

Sample Input 3

10 4
3 1
4 1
5 9
2 6

Sample Output 3

3


Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


local N = io.read("l")
local diff = string.byte("0")

local dig_sum = 0
for i = 1, N:len() do
	dig_sum = dig_sum + N:byte(i) - diff
end

print((dig_sum % 9 == 0) and "Yes" or "No")

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


local mmi, mma = math.min, math.max
local n = io.read("*n")
local r = 0
local max = 0
for i = 1, n do
  local a = io.read("*n")
  if a < max then r = r + max - a
  elseif max < a then max = a
  end
end
print(r)

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

1 \leq N \leq 2\times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


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
    local value = list[first]
    list[first] = nil
    list.first = first + 1
    return value
end

function List.popright (list)
    local last = list.last
    local value = list[last]
    list[last] = nil
    list.last = last - 1
    return value
end

function List.empty (list)
    return list.first > list.last
end

----------

local h,w=io.read("n","n")
local ch,cw=io.read("n","n")
local dh,dw=io.read("n","n","l")

local s={}
for i=1,h do
    local input=io.read()
    s[i]={}
    for j=1,w do
        s[i][j]=input:sub(j,j)
    end
end

local checkin=List.new()
local checked=List.new()
List.pushright(checkin,{ch,cw})

local cost={}
local INF=math.maxinteger
for i=1,h do
    cost[i]={}
    for j=1,w do
        cost[i][j]=INF
    end
end
cost[ch][cw]=0
local dx={1,0,-1,0}
local dy={0,1,0,-1}

while (not List.empty(checkin)) or (not List.empty(checked)) do
    if not List.empty(checkin) then
        local q=List.popleft(checkin)
        List.pushright(checked,q)
        local x,y=q[1],q[2]
        for i=1,4 do
            local nx,ny=x+dx[i],y+dy[i]
            local checker=(nx<1 or nx>h or ny<1 or ny>w)
            if not checker and s[nx][ny]~="#"then
                if cost[x][y]<cost[nx][ny] then
                    cost[nx][ny]=cost[x][y]
                    List.pushright(checkin,{nx,ny})
                end
            end
        end
    else
        local q=List.popleft(checked)
        local x,y=q[1],q[2]
        for dx=-2,2 do
            for dy=-2,2 do
                local nx,ny=x+dx,y+dy
                local checker=(nx<1 or nx>h or ny<1 or ny>w)
                if not checker and s[nx][ny]~="#"then
                    if cost[x][y]+1<cost[nx][ny] then
                        cost[nx][ny]=cost[x][y]+1
                        List.pushright(checkin,{nx,ny})
                    end
                end
            end
        end
    end
end

print(cost[dh][dw]<INF and cost[dh][dw] or -1)

Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

4 4
1 1
4 4
..#.
..#.
.#..
.#..

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

4 4
1 4
4 1
.##.
####
####
.##.

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2


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(dimensi0n, default_val) assert(type(default_val) ~= 'table') local n=dimensi0n local m={}if default_val~=nil then m[1]={__index=function()return default_val end}end for i=2,n do m[i]={__index=function(p, k)local c=setmetatable({},m[i-1])rawset(p,k,c)return c end}end return setmetatable({},m[n])end
--
local S = read.l()
if S == 'SSS' then
    print(0)
elseif S == 'RSS' or S == 'SRS' or S == 'SSR' or S == 'RSR' then
    print(1)
elseif S == 'RRR' then
    print(3)
else
    print(2)
end

Score : 100 points

Problem Statement

We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is S, it means it was sunny on the i-th day; if that character is R, it means it was rainy on that day.

Find the maximum number of consecutive rainy days in this period.

Constraints

|S| = 3

Each character of S is S or R.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of consecutive rainy days in the period.

Sample Input 1

RRS

Sample Output 1

2

We had rain on the 1-st and 2-nd days in the period. Here, the maximum number of consecutive rainy days is 2, so we should print 2.

Sample Input 2

SSS

Sample Output 2

0

It was sunny throughout the period. We had no rainy days, so we should print 0.

Sample Input 3

RSR

Sample Output 3

1

We had rain on the 1-st and 3-rd days - two "streaks" of one rainy day, so we should print 1.


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(dimensi0n, default_val) assert(type(default_val) ~= 'table') local n=dimensi0n local m={}if default_val~=nil then m[1]={__index=function()return default_val end}end for i=2,n do m[i]={__index=function(p, k)local c=setmetatable({},m[i-1])rawset(p,k,c)return c end}end return setmetatable({},m[n])end
--
local N = read.n()
local L = read.N(N)

local ans = 0
for i=1,N-2 do
    for j=i+1,N-1 do
        for k=j+1,N do
            if L[i] ~= L[j] and L[i] ~= L[k] and L[j] ~= L[k] then
                local t = {L[i], L[j], L[k]}
                table.sort(t)
                local a,b,c = table.unpack(t)
                if a < b + c and b < c + a and c < a + b then
                    ans = ans + 1
                end
            end
        end
    end
end
print(ans)

Score : 200 points

Problem Statement

We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.

In how many ways can we choose three of the sticks with different lengths that can form a triangle?

That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:

L_i, L_j, and L_k are all different.

There exists a triangle whose sides have lengths L_i, L_j, and L_k.

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 \cdots L_N

Output

Print the number of ways to choose three of the sticks with different lengths that can form a triangle.

Sample Input 1

5
4 4 9 7 5

Sample Output 1

5

The following five triples (i, j, k) satisfy the conditions: (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 4, 5), and (3, 4, 5).

Sample Input 2

6
4 5 4 3 3 5

Sample Output 2

8

We have two sticks for each of the lengths 3, 4, and 5. To satisfy the first condition, we have to choose one from each length.

There is a triangle whose sides have lengths 3, 4, and 5, so we have 2 ^ 3 = 8 triples (i, j, k) that satisfy the conditions.

Sample Input 3

10
9 4 6 1 9 6 10 6 6 8

Sample Output 3

39

Sample Input 4

2
1 1

Sample Output 4

0

No triple (i, j, k) satisfies 1 \leq i < j < k \leq N, so we should print 0.


x, k, d = io.read("*n","*n","*n")

x = math.abs(x)

if math.abs(x) // d >= k then
  print(math.abs(x) - k*d)
elseif (k - x // d) % 2 == 0 then
  print(math.abs(x - x // d * d))
else
  print(math.min(math.abs(x - x // d * d - d), math.abs(x - x // d * d + d)))
end

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.


x, k, d = io.read("*n","*n","*n")

x = math.abs(x)

if math.abs(x) // d >= k then
  print(math.abs(x) - k*d)
else
  k = k - x // d
  x = x - x // d * d
  if (k % 2 == 1) then x = math.abs(x - d) end
  print(x)
end


local mfl, mce = math.floor, math.ceil
local n, k = io.read("*n", "*n")
local p, c = {}, {}
for i = 1, n do
  p[i] = io.read("*n")
end
for i = 1, n do
  c[i] = io.read("*n")
end
local asked = {}
for i = 1, n do
  asked[i] = false
end
local function findstart()
  for i = 1, n do
    if not asked[i] then return i end
  end
  return false
end
local ret = -1000000007LL
local function mma_l(a, b) return a < b and b or a end
while true do
  local spos = findstart()
  if not spos then break end
  local route = {spos}
  local sum = 0LL + c[spos]
  local src = spos
  asked[spos] = true
  while true do
    local dst = p[src]
    if asked[dst] then break end
    asked[dst] = true
    table.insert(route, dst)
    sum = sum + c[dst]
    src = dst
  end
  local len = #route
  if 0LL < sum then
    local ofst = mfl(k / len)
    local rem = k - ofst * len
    ofst = sum * ofst
    ret = mma_l(ret, ofst)
    for i = 1, len do
      local v = 0LL
      local src = route[i]
      for j = 1, rem do
        local dst = p[src]
        v = v + c[dst]
        ret = mma_l(ret, ofst + v)
        src = dst
      end
    end
  else
    for i = 1, len do
      local v = 0LL
      local src = route[i]
      for j = 1, len do
        local dst = p[src]
        v = v + c[dst]
        ret = mma_l(ret, v)
        src = dst
      end
    end
  end
end
ret = tostring(ret):gsub("LL", "")
print(ret)

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


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(dimensi0n, default_val) assert(type(default_val) ~= 'table') local n=dimensi0n local m={}if default_val~=nil then m[1]={__index=function()return default_val end}end for i=2,n do m[i]={__index=function(p, k)local c=setmetatable({},m[i-1])rawset(p,k,c)return c end}end return setmetatable({},m[n])end
local function tostringxx(o, depth) depth = depth or 0 if depth > 10 then return "<too deep!>" end if o == _G then return "<_G>" end local indent0 = (" "):rep((depth) * 2) local indent1 = (" "):rep((depth+1) * 2) local indent2= (" "):rep((depth+2) * 2) if type(o) == 'table' then local keys = {} local types = {} for k in pairs(o) do types[type(k)] = true table.insert(keys, k) end local types_count = 0 local lasttype for k in pairs(types) do types_count = types_count + 1 lasttype = k end if types_count == 1 and (lasttype == 'string' or lasttype == 'number') then table.sort(keys) end local inside = {} for i=1,#keys do local k = keys[i] local v = o[k] if type(k) == 'string' then k = string.format('%q', k) end table.insert(inside, indent1 .. '['..tostring(k)..'] = ' .. tostringxx(v, depth + 1)) end return '{\n' .. table.concat(inside, ',\n') .. '\n' .. indent0 .. '}' else if type(o) == 'string' then o = string.format('%q', o) end return tostring(o) end end
local function richtraceback() local x = 2 while true do local info = debug.getinfo(x) if not info then break end local fname = '<' .. info.short_src .. ":" .. info.linedefined .. ">" if info.name then fname = info.name end print(info.short_src .. ":" .. info.currentline .. ": in " .. ("%q"):format(fname)) print(" LOCALS:") local p = 1 while true do local name, val = debug.getlocal(x,p) if not name then break end print(" " .. name .. ": " .. tostringxx(val, 3)) p = p + 1 end print(" UPVALUES:") for p=1,info.nups do local name, val = debug.getupvalue(info.func,p) if not name then break end print(" " .. name .. ": " .. tostringxx(val, 3)) end x = x + 1 end end
local function myassert(b) if not b then richtraceback() error("assertion failed") end end
--
local max = math.max

local R, C, K = read.nnn()
local item = array(1,0)
for i=1,K do
    local r,c,v = read.nnn()
    item[r*C + c] = v
end

local target1
local target2
local function chmax1(g,val)
    target1[g] = max(target1[g], val)
end
local function chmax2(g,val)
    target2[g] = max(target2[g], val)
end
local dp = array(2,0)

dp[1][0] = 0
dp[1][1] = item[1*C+1]
for r=1,R do
    for c=1,C do
        target1 = dp[c]
        target2 = dp[c+1]
        local rval = item[r*C+c+1]
        local dval = item[(r+1)*C+c]
        local cur0 = target1[0]
        local cur1 = target1[1]
        local cur2 = target1[2]
        local cur3 = target1[3]
        target1[0] = 0
        target1[1] = 0
        target1[2] = 0
        target1[3] = 0
        chmax1(1,cur0+dval)
        chmax1(0,cur0)
        chmax1(1,cur1+dval)
        chmax1(0,cur1)
        chmax1(1,cur2+dval)
        chmax1(0,cur2)
        chmax1(1,cur3+dval)
        chmax1(0,cur3)
        chmax2(0+1,cur0+rval)
        chmax2(0,cur0)
        chmax2(1+1,cur1+rval)
        chmax2(1,cur1)
        chmax2(2+1,cur2+rval)
        chmax2(2,cur2)
        chmax2(3+1,cur3+rval)
        chmax2(3,cur3)
    end
end
print(max(dp[C][0],dp[C][1],dp[C][2],dp[C][3]))

Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

2 2 3
1 1 3
2 1 4
1 2 5

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

2 5 5
1 1 3
2 4 20
1 2 1
1 3 4
1 4 2

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142


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(dimensi0n, default_val) assert(type(default_val) ~= 'table') local n=dimensi0n local m={}if default_val~=nil then m[1]={__index=function()return default_val end}end for i=2,n do m[i]={__index=function(p, k)local c=setmetatable({},m[i-1])rawset(p,k,c)return c end}end return setmetatable({},m[n])end
local function tostringxx(o, depth) depth = depth or 0 if depth > 10 then return "<too deep!>" end if o == _G then return "<_G>" end local indent0 = (" "):rep((depth) * 2) local indent1 = (" "):rep((depth+1) * 2) local indent2= (" "):rep((depth+2) * 2) if type(o) == 'table' then local keys = {} local types = {} for k in pairs(o) do types[type(k)] = true table.insert(keys, k) end local types_count = 0 local lasttype for k in pairs(types) do types_count = types_count + 1 lasttype = k end if types_count == 1 and (lasttype == 'string' or lasttype == 'number') then table.sort(keys) end local inside = {} for i=1,#keys do local k = keys[i] local v = o[k] if type(k) == 'string' then k = string.format('%q', k) end table.insert(inside, indent1 .. '['..tostring(k)..'] = ' .. tostringxx(v, depth + 1)) end return '{\n' .. table.concat(inside, ',\n') .. '\n' .. indent0 .. '}' else if type(o) == 'string' then o = string.format('%q', o) end return tostring(o) end end
local function richtraceback() local x = 2 while true do local info = debug.getinfo(x) if not info then break end local fname = '<' .. info.short_src .. ":" .. info.linedefined .. ">" if info.name then fname = info.name end print(info.short_src .. ":" .. info.currentline .. ": in " .. ("%q"):format(fname)) print(" LOCALS:") local p = 1 while true do local name, val = debug.getlocal(x,p) if not name then break end print(" " .. name .. ": " .. tostringxx(val, 3)) p = p + 1 end print(" UPVALUES:") for p=1,info.nups do local name, val = debug.getupvalue(info.func,p) if not name then break end print(" " .. name .. ": " .. tostringxx(val, 3)) end x = x + 1 end end
local function myassert(b) if not b then richtraceback() error("assertion failed") end end
--
local max = math.max

local R, C, K = read.nnn()
local item = array(1,0)
for i=1,K do
    local r,c,v = read.nnn()
    item[r*C + c] = v
end

local dp = array(2,0)

dp[1][0] = 0
dp[1][1] = item[1*C+1]
for r=1,R do
    for c=1,C do
        local target1 = dp[c]
        local target2 = dp[c+1]
        local function chmax1(g,val)
            target1[g] = max(target1[g], val)
        end
        local function chmax2(g,val)
            target2[g] = max(target2[g], val)
        end
        local rval = item[r*C+c+1]
        local dval = item[(r+1)*C+c]
        local cur0 = target1[0]
        local cur1 = target1[1]
        local cur2 = target1[2]
        local cur3 = target1[3]
        target1[0] = 0
        target1[1] = 0
        target1[2] = 0
        target1[3] = 0
        chmax1(1,cur0+dval)
        chmax1(0,cur0)
        chmax1(1,cur1+dval)
        chmax1(0,cur1)
        chmax1(1,cur2+dval)
        chmax1(0,cur2)
        chmax1(1,cur3+dval)
        chmax1(0,cur3)
        chmax2(0+1,cur0+rval)
        chmax2(0,cur0)
        chmax2(1+1,cur1+rval)
        chmax2(1,cur1)
        chmax2(2+1,cur2+rval)
        chmax2(2,cur2)
        chmax2(3+1,cur3+rval)
        chmax2(4,cur3)
    end
end
print(max(dp[C][0],dp[C][1],dp[C][2],dp[C][3]))


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(dimensi0n, default_val) assert(type(default_val) ~= 'table') local n=dimensi0n local m={}if default_val~=nil then m[1]={__index=function()return default_val end}end for i=2,n do m[i]={__index=function(p, k)local c=setmetatable({},m[i-1])rawset(p,k,c)return c end}end return setmetatable({},m[n])end
local function tostringxx(o, depth) depth = depth or 0 if depth > 10 then return "<too deep!>" end if o == _G then return "<_G>" end local indent0 = (" "):rep((depth) * 2) local indent1 = (" "):rep((depth+1) * 2) local indent2= (" "):rep((depth+2) * 2) if type(o) == 'table' then local keys = {} local types = {} for k in pairs(o) do types[type(k)] = true table.insert(keys, k) end local types_count = 0 local lasttype for k in pairs(types) do types_count = types_count + 1 lasttype = k end if types_count == 1 and (lasttype == 'string' or lasttype == 'number') then table.sort(keys) end local inside = {} for i=1,#keys do local k = keys[i] local v = o[k] if type(k) == 'string' then k = string.format('%q', k) end table.insert(inside, indent1 .. '['..tostring(k)..'] = ' .. tostringxx(v, depth + 1)) end return '{\n' .. table.concat(inside, ',\n') .. '\n' .. indent0 .. '}' else if type(o) == 'string' then o = string.format('%q', o) end return tostring(o) end end
local function richtraceback() local x = 2 while true do local info = debug.getinfo(x) if not info then break end local fname = '<' .. info.short_src .. ":" .. info.linedefined .. ">" if info.name then fname = info.name end print(info.short_src .. ":" .. info.currentline .. ": in " .. ("%q"):format(fname)) print(" LOCALS:") local p = 1 while true do local name, val = debug.getlocal(x,p) if not name then break end print(" " .. name .. ": " .. tostringxx(val, 3)) p = p + 1 end print(" UPVALUES:") for p=1,info.nups do local name, val = debug.getupvalue(info.func,p) if not name then break end print(" " .. name .. ": " .. tostringxx(val, 3)) end x = x + 1 end end
local function myassert(b) if not b then richtraceback() error("assertion failed") end end
--
local max = math.max

local R, C, K = read.nnn()
local item = array(1,0)
for i=1,K do
    local r,c,v = read.nnn()
    item[r*C + c] = v
end

local dp,dp_next = array(2,0),array(2,0)
local function chmax1(c,g,val)
    dp[c][g] = max(dp[c][g], val)
end
local function chmax2(c,g,val)
    dp_next[c][g] = max(dp_next[c][g], val)
end

dp[1][0] = 0
dp[1][1] = item[1*C+1]
for r=1,R do
    for c=1,C do
        for g=0,3 do
            dp_next[c][g] = 0
        end
        for g=0,3 do
            local curval = dp[c][g]
            chmax1(c+1,g+1,curval+item[r*C+c+1])
            chmax1(c+1,g,curval)
            chmax2(c,1,curval+item[(r+1)*C+c])
            chmax2(c,0,curval)
        end
    end
    dp, dp_next = dp_next, dp
end
print(max(dp[C][0],dp[C][1],dp[C][2],dp[C][3]))