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])
  local z = {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)
    table.insert(z, v)
    if v == 1 then break end
    v = st1:left_bound(1, v - 1)
  end
  for j = 1, #z - 1 do
    st1:setValue(z[j], false)
  end
  st1:setValue(z[#z], 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

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

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

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 st2 = SegTree.new(n, orfunc, false)
for i = n, 1, -1 do
  local src = xidx[i]
  local v = st2:right_bound(ys[src], n)
  while v <= n do
    local dst = yidx[v]
    local rs, rd = uf_findroot(src), uf_findroot(dst)
    parent[rd], parent[dst] = rs, rs
    st2:setValue(v, false)
    if v == n then break end
    v = st2:right_bound(v + 1, n)
  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()
if n == "1" then print(1) os.exit() end
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-2 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 n = io.read("*n")
local len = 0
local maxlen = 0
for i = 1, n do
  a, b = io.read("*n", "*n")
  if a == b then
    len = len + 1
  else
    len = 0
  end
  maxlen = math.max(maxlen, len)
end
print(3 <= maxlen and "Yes" or "No")


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


-- Vicfred
-- https://atcoder.jp/contests/abc178/tasks/abc178_a
-- implementation

x = io.read("*n")

print(x ~ 1)

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


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 mod=1000000007
local function powmod(x,n)
    local a=1
    for i=1,n do
        a=(a*x)%mod
    end
    return a
end

----------

local n=io.read("n")
local total=powmod(10,n)
local zorn=powmod(9,n)
local zandn=powmod(8,n)
print((total-zorn-zorn+zandn)%mod)

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


-- Vicfred
-- https://atcoder.jp/contests/abc178/tasks/abc178_c
-- math

function binpow(a, b, m)
    a = a % m
    res = 1
    while b > 0 do
        if (b % 2) == 1 then
            res = (res * a) % m
        end
        a = (a * a) % m
        b = b // 2
    end

    return res
end

mod = 1000000007

n = io.read("*n")

ans = binpow(10, n, mod) - binpow(9, n, mod) - binpow(9, n, mod) + binpow(8, n, mod)
ans = ans + mod
ans = ans % mod
print(ans)


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
for i = 1, n do
	local num = nin_pow + ((eig_pow_t[i - 1] or 1) * (nin_pow_t[n - i] or 1)) % 1000000007
	nin_pow = num % 1000000007
end
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)


local mod = 1000000007
local mfl = math.floor

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

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

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

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

local n = io.read("*n")
local r1 = modpow(8, n)
local r2 = modpow(9, n)
local all = modpow(10, n)
print((all - r2 - r2 + r1) % mod)


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.opValue = function(self, idx, value)
  self.stage[self.stagenum][idx] = self.func(self.stage[self.stagenum][idx], value)
  self:update(idx)
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local function axiscomp(ary)
  local z = {}
  for i = 1, #ary do
    z[i] = ary[i]
  end
  table.sort(z)
  local ac, acinv = {}, {}
  local cur = 0
  for i = 1, #z do
    if not acinv[z[i]] then
      cur = cur + 1
      ac[cur] = z[i]
      acinv[z[i]] = cur
    end
  end
  return ac, acinv
end

local n = io.read("*n")
local xs, ys = {}, {}
local idx = {}
for i = 1, n do
  xs[i], ys[i] = io.read("*n", "*n")
  idx[i] = i
end
table.sort(idx, function(a, b) return xs[a] < xs[b] end)
local ycomp, yinv = axiscomp(ys)
local st_xpy = SegTree.new(n, mmi, 10 * 1000000007)
local st_xmy = SegTree.new(n, mmi, 10 * 1000000007)
local ret = 0
for i = 1, n do
  local x, y = xs[idx[i]], ys[idx[i]]
  local ypos = yinv[y]
  ret = mma(ret, x + y - st_xpy:getRange(1, ypos))
  ret = mma(ret, x - y - st_xmy:getRange(ypos, n))
  st_xpy:opValue(ypos, x + y)
  st_xmy:opValue(ypos, x - y)
end
print(ret)

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")
  u, v = u + 1, v + 1
  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


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


local WhiteBlack = {}

WhiteBlack.create = function(self)
  self.edge = {}
  self.invedge = {}
  self.leftnode = {}
  self.rightmatched = {}
  self.route = {}
  self.routelen = 0
  self.asked = {}
  self.finaldst = {}
end

WhiteBlack.addNode = function(self, node, isLeft)
  if isLeft then
    table.insert(self.leftnode, node)
    self.edge[node] = {}
  else
    self.invedge[node] = {}
  end
end

WhiteBlack.addEdge = function(self, src, dst)
  assert(self.edge[src])
  self.edge[src][dst] = 1
  self.invedge[dst][src] = 0
end

WhiteBlack.dfs = function(self)
  local src = self.route[self.routelen]
  if self.routelen % 2 == 1 then
    for dst, c in pairs(self.edge[src]) do
      if c == 1 and not self.asked[dst] then
        self.asked[dst] = true
        self.routelen = self.routelen + 1
        self.route[self.routelen] = dst
        local ret = self:dfs()
        if ret then return true end
        self.routelen = self.routelen - 1
      end
    end
  else
    if not self.rightmatched[src] then
      self.rightmatched[src] = true
      return true
    end
    for dst, c in pairs(self.invedge[src]) do
      if c == 1 and not self.asked[dst] then
        self.asked[dst] = true
        self.routelen = self.routelen + 1
        self.route[self.routelen] = dst
        local ret = self:dfs()
        if ret then return true end
        self.routelen = self.routelen - 1
      end
    end
  end
  return false
end

WhiteBlack.run = function(self, spos)
  local tasks = {spos}
  local tasked = {}
  local dstpos = 0
  tasked[spos] = true
  for k, _u in pairs(self.asked) do
    self.asked[k] = false
  end
  self.asked[spos] = true
  self.routelen = 1
  self.route[1] = spos
  local found = self:dfs()
  if found then
    for i = 1, self.routelen - 1 do
      local src, dst = self.route[i], self.route[i + 1]
      if i % 2 == 1 then
        self.edge[src][dst] = 0
        self.invedge[dst][src] = 1
        self.finaldst[src] = dst
      else
        self.edge[dst][src] = 1
        self.invedge[src][dst] = 0
      end
    end
    return true
  else return false end
end

WhiteBlack.getMatchCount = function(self)
  local cnt = 0
  local lnodenum = #self.leftnode
  for i = 1, lnodenum do
    local res = self:run(self.leftnode[i])
    if res then cnt = cnt + 1 end
  end
  return cnt
end

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

local wb = WhiteBlack.new()
local h, w = io.read("*n", "*n", "*l")
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)
    wb:addNode(idx, (i + j) % 2 == 0)
  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
        wb:addEdge(idx, idx + w)
      else
        wb:addEdge(idx + w, 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
        wb:addEdge(idx, idx + 1)
      else
        wb:addEdge(idx + 1, idx)
      end
    end
  end
end
local cnt = wb:getMatchCount()
print(cnt)
for l, r in pairs(wb.finaldst) do
  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
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
  local edge_dst, edge_cap, edge_cost = self.edge_dst, self.edge_cap, self.edge_cost
  local edge_dst_invedge_idx = self.edge_dst_invedge_idx
  local len = self.len
  local sub_graph_flag = self.sub_graph_flag
  local sub_graph_v = self.sub_graph_v
  local sub_graph_edgeidx = self.sub_graph_edgeidx
  for i = 1, #edge_dst[invsrc] do
    local invdst = edge_dst[invsrc][i]
    local j = edge_dst_invedge_idx[invsrc][i]
    if 0 < edge_cap[invdst][j]
    and len[invdst] + edge_cost[invdst][j] == len[invsrc]
    and not sub_graph_flag[invdst] then
      self.sub_graph_size = self.sub_graph_size + 1
      sub_graph_v[self.sub_graph_size] = invdst
      sub_graph_edgeidx[self.sub_graph_size - 1] = j
      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 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
  len[self.spos] = 0
  local n = self.n
  for irp = 1, n do
    for src = 1, n do
      for i = 1, #edge_dst[src] do
        local cap = edge_cap[src][i]
        if 0 < cap then
          local dst = edge_dst[src][i]
          local cost = edge_cost[src][i]
          if len[src] + cost < len[dst] then
            len[dst] = len[src] + cost
          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 TFFT = {}

TFFT.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

TFFT.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

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

TFFT.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

TFFT.fft = function(self, ary)
  return self:fft_common(ary, self.wmul)
end
TFFT.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)
TFFT:initialize()
local a, b = {}, {}
local n, m = io.read("*n", "*n")
for i = 1, TFFT.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 = TFFT:fft(a)
local bt = TFFT:fft(b)
for i = 1, TFFT.n do
  at[i] = TFFT:mul(at[i], bt[i])
end
local c = TFFT: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


--[[------------------------------------------------------------------------]]--
--- `0 <= num <= 10^8` return minimum non-negative `x` s.t. `n <= 2**x`
local function ceil_pow2(num)
	local x = 0
	while (1 << x) < num do
		x = x + 1
	end
	return x
end

--- `1 <= index < len`
local function update(_, index)
	_.vec[index] = _.operation_fn(
		_.vec[2 * index], _.vec[2 * index + 1]
	)
end

local SegTree ={}

--- `0 <= #element_count_or_vec <= 10^8`
--- (1): 長さ`element_count_or_vec`の数列`vec`を作ります。
--- 初期値は全部`init_val_fn()`です。
--- (2): 長さ`#element_count_or_vec`の数列`vec`を作ります。
--- `element_count_or_vec`の内容が初期値となります。
--- `O(n)`
function SegTree.new(operation_fn, init_val_fn, element_count_or_vec)
	if type(element_count_or_vec) == "number" then
		assert(
			0 <= element_count_or_vec
				and element_count_or_vec <= 100000000
		)
		local vec = {}
		for i = 1, element_count_or_vec do
			vec[i] = init_val_fn()
		end
		return SegTree.new(operation_fn, init_val_fn, vec)
	end
	assert(
		type(element_count_or_vec) == "table",
		"arg error! need number or table"
	)
	local vec_len = #element_count_or_vec
	assert(0 <= vec_len and vec_len <= 100000000)
	local log = ceil_pow2(vec_len)
	local len = 1 << log
	local vec = {}
	local _ = {
		vec_len = vec_len,
		log = log,
		len = len,
		vec = vec,
		operation_fn = operation_fn,
		init_val_fn = init_val_fn,
		update = update
	}
	for i = 1, 2 * len do
		vec[i] = init_val_fn()
	end
	for i = 1, vec_len do
		vec[len + i - 1] = element_count_or_vec[i];
	end
	for i = len - 1, 1, -1 do
		update(_, i)
	end
	return setmetatable({_ = _}, {__index = SegTree})
end

--- `1 <= index <= #element_count_or_vec`
--- `vec[index]`に`value`を代入します。
--- `O(log(n))`
function SegTree:set(index, value)
	assert(1 <= index and index <= self._.vec_len)
	index = index - 1 + self._.len
	self._.vec[index] = value
	for i = 1, self._.log do
		update(self._, index >> i)
	end
end

--- `1 <= index <= #element_count_or_vec`
--- `vec[index]`を返します。
--- `O(1)`
function SegTree:get(index)
	assert(1 <= index and index <= self._.vec_len)
	return self._.vec[index - 1 + self._.len]
end

--- `1 <= left <= right <= #element_count_or_vec`
--- `operation_fn(vec[left], ..., vec[right])`を、
--- モノイドの性質を満たしていると仮定して計算します。
--- `O(log(n))`
function SegTree:operate_between(left, right)
	assert(1 <= left and left <= right and right <= self._.vec_len)
	local vec = self._.vec
	local operation_fn = self._.operation_fn

	left = left - 1 + self._.len
	right = right - 1 + self._.len
	local operated_left = vec[left]
	local operated_right = vec[right]
	while left < right do
		-- 今のleftが奇数のとき、つまり引数のleftが偶数のとき
		if left & 1 == 1 then
			operated_left = operation_fn(operated_left, vec[left])
			left = left + 1
		end
		if right & 1 == 1 then
			right = right - 1
			operated_right = operation_fn(vec[right], operated_right)
		end
		left = left >> 1
		right = right >> 1
	end
	return operation_fn(operated_left, operated_right)
end

--- `op(a[1], ..., a[n])`を計算します。`n = 0`のときは`init_val_fn()`を返します。
--- `O(1)`
function SegTree:operate_all()
	return self._.vec[1]
end

--- `1 <= left <= #element_count_or_vec`
--- 関数`bool_fn_arg_val(x) -> bool`を定義する必要があります。
--- `x`は`vec`の値が入ります。
--- `init_val_fn()`の値を含む範囲が`true`になるようにする(題意の`not`にあたる？)
--- `segtree`の上で二分探索をします。`left`が大きくなる方向に調べていきます。
--- `O(log(n))`
function SegTree:search_to_right_from(left, bool_fn_arg_val)
	assert(1 <= left and left <= self._.vec_len)
	assert(bool_fn_arg_val(self._.init_val_fn()))
	local operation_fn = self._.operation_fn
	local vec = self._.vec
	local len = self._.len

	left = left - 1 + len
	local value = self._.init_val_fn()
	while true do
		while left % 2 == 0 do
			left = left >> 1
		end
		if not bool_fn_arg_val(operation_fn(value, vec[left])) then
			while left < len do
				left = 2 * left
				if bool_fn_arg_val(operation_fn(value, vec[left])) then
					value = operation_fn(value, vec[left])
					left = left + 1
				end
			end
			return left + 1 - len
		end
		value = operation_fn(value, vec[left])
		left = left + 1

		if (left & -left) == left then
			return self._.vec_len + 1
		end
	end
end

--- `1 <= right <= #element_count_or_vec`
--- 関数`bool_fn_arg_val(x) -> bool`を定義する必要があります。
--- `x`は`vec`の値が入ります。
--- `init_val_fn()`の値を含む範囲が`true`になるようにする(題意の`not`にあたる？)
--- `segtree`の上で二分探索をします。`right`が小さくなる方向に調べていきます
--- `O(log(n))`
function SegTree:min_left(right, bool_fn_arg_val)
	assert(1 <= right and right <= self._.vec_len)
	assert(bool_fn_arg_val(self._.init_val_fn()))
	local operation_fn = self._.operation_fn
	local vec = self._.vec
	local len = self._.len

	right = right - 1 + len
	local value = self._.init_val_fn()
	while true do
		while right > 1 and right % 2 == 1 do
			right = right >> 1
		end
		if not bool_fn_arg_val(operation_fn(vec[right], value)) then
			while right < len do
				right = 2 * right + 1
				if bool_fn_arg_val(operation_fn(vec[right], value)) then
					value = operation_fn(vec[right], value)
					right = right - 1
				end
			end
			return right + 1 - len
		end
		value = operation_fn(vec[right], value)
		right = right - 1

		if (right & -right) == right then
			return 0
		end
	end
end

--[[------------------------------------------------------------------------]]--

local read = io.read
local insert = table.insert

local n, q = read("n", "n")
local a_t = {}
for i = 1, n do
	a_t[i] = read("n")
end

local segTree = SegTree.new(
	math.max,
	function() return -1 end,
	a_t
)

local out_t = {}
for i = 1, q do
	local t = read("n")
	if t == 1 then
		local x_i, v_i = read("n", "n")
		segTree:set(x_i, v_i)
	elseif t == 2 then
		local l_i, r_i = read("n", "n")
		insert(out_t, segTree:operate_between(l_i, r_i))
	else
		local x_i, v_i = read("n", "n")
		insert(
			out_t,
			segTree:search_to_right_from(x_i, function(x) return x < v_i end)
		)
	end
end

print(table.concat(out_t, "\n"))

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
    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
  local t, l, r = io.read("*n", "*n", "*n")
  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+) (%d+)")
d, t, s = tonumber(d), tonumber(t), tonumber(s)

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.


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

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

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


local d, t, s = io.read("n", "n", "n")

print((t >= d / s) and "Yes" or "No")


local n, m = 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, m do
  local a, b = io.read("*n", "*n")
  local ra, rb = uf_findroot(a), uf_findroot(b)
  parent[rb], parent[b] = ra, ra
end
local map = {}
for i = 1, n do
  local r = uf_findroot(i)
  if not map[r] then map[r] = 1
  else map[r] = map[r] + 1
  end
end
local max = 0
for _k, v in pairs(map) do
  max = max < v and v or max
end
print(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()
local s=0
for i=1,#n do
    s=s+tonumber(n:sub(i,i))
end
print(s%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 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 unpack = table.unpack or unpack
--
local H, W = read.nn()
local Ch, Cw = read.nn()
local Dh, Dw = read.nnl()
local S = {}
for i=1,H do
    S[i] = read.l():totable()
end
local function isopen(h, w)
    return S[h] and S[h][w] == '.'
end

local function make_deque()
    local a = {}
    -- elements exist at a[i] where left < i < right
    local left = 0
    local right = 1
    local function count()
        return right - left - 1
    end
    local function push_left(x)
        a[left] = x
        left = left - 1
        return x
    end
    local function pop_left()
        left = left + 1
        local x = a[left]
        a[left] = nil
        return x
    end
    local function push_right(x)
        a[right] = x
        right = right + 1
        return x
    end
    local function pop_right()
        right = right - 1
        local x = a[right]
        a[right] = nil
        return x
    end
    return count, push_left, pop_left, push_right, pop_right, a
end
local count, push_left, pop_left, push_right, pop_right = make_deque()

local from_src = array(2)
local neigh = {}
for i=-2,2 do
    for j=-2,2 do
        if i == 0 and j == 0 then
        elseif math.abs(i) + math.abs(j) == 1 then
        else
            table.insert(neigh, {i,j})
        end
    end
end

push_left({Ch, Cw, 0})
from_src[Ch][Cw] = 0
while count() > 0 do
    --print(tostringxx(a))
    local sh, sw, cur_cost = unpack(pop_left())
    -- LRDU
    local dh, dw = -1, 0
    for _=1,4 do
        dh, dw = dw, -dh -- rotate pi/2
        local th, tw = sh+dh, sw+dw
        if not isopen(th, tw) then
            goto next
        end
        if not from_src[th][tw] or from_src[th][tw] > cur_cost then
            from_src[th][tw] = cur_cost
            push_left({th, tw, cur_cost})
        end
        ::next::
    end
    cur_cost = cur_cost + 1
    for _,dhdw in ipairs(neigh) do
        dh, dw = unpack(dhdw)
        local th, tw = sh+dh, sw+dw
        if not isopen(th, tw) then
            goto next
        end
        if not from_src[th][tw] or from_src[th][tw] > cur_cost then
            from_src[th][tw] = cur_cost
            push_right({th, tw, cur_cost})
        end
        ::next::
    end
end
print(from_src[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 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
--
-- heap
local Heap = {}
function Heap.new(upper_func)
    local self = setmetatable({}, {__index = Heap})
    self.a = {}
    self.upper_func = upper_func
    self.upper = function(k1, k2)
        assert(k1 < k2)
        if k1 == 0 then
            return false
        else
            return upper_func(self.a[k1], self.a[k2])
        end
    end
    self.lower = function(k1, k2)
        return not self.upper(k1, k2)
    end
    return self
end

function Heap:count()
    return #self.a
end

function Heap:_swap(k1, k2)
    local old_k1 = self.a[k1]
    self.a[k1] = self.a[k2]
    self.a[k2] = old_k1
end

function Heap:upheap(newk)
    local ku = math.floor(newk / 2)
    local k = newk
    while ku > 0 and self.lower(ku, k) do
        self:_swap(ku, k)
        k = math.floor(k/2)
        ku = math.floor(ku/2)
    end
end

function Heap:insertq(e)
    table.insert(self.a, e)
    self:upheap(#self.a)
end

function Heap:downheap(newk)
    local k = newk
    while k <= math.floor(#self.a/2) do
        local kdl = k*2
        local kdr = kdl + 1
        local kd
        if kdr <= #self.a and self.lower(kdl, kdr) then
            kd = kdr
        else
            kd = kdl
        end
        if self.upper(k, kd) then
            break
        end
        self:_swap(k, kd)
        k = kd
    end
end

function Heap:top()
    assert(#self.a >= 1)
    return self.a[1]
end

function Heap:remove_top()
    assert(#self.a >= 1)
    local v = self.a[1]
    self:_swap(1, #self.a)
    table.remove(self.a)
    self:downheap(1)
    return v
end
--------------------------------------
local K1 = 1000
local INF = math.floor(10^18)
--
local abs = math.abs
local floor = math.floor
--
local H, W = read.nn()
local Ch, Cw = read.nn()
local Dh, Dw = read.nnl()
local S = {}
for i=1,H do
    S[i] = read.l():totable()
end
local function isopen(h, w)
    return S[h] and S[h][w] == '.'
end
local function getid(h, w)
    return w + h * K1
end
local function gethw(id)
    local h, w = floor(id / K1), id % K1
    return h, w
end
local function make_tuple(id, weight)
    return {weight, id}
end
local function unpack_tuple(t)
    return t[1], t[2]
end

-- dijkstra's algorithm
local function find_mincost(srch, srcw, dsth, dstw)
    local srcid = getid(srch, srcw)
    local dstid = getid(dsth, dstw)
    local from_src = {} -- if v is unreachable, from_src[v] == nil.
    from_src[srcid] = 0
    local q = Heap.new(function (v1, v2)
        --local w1 = unpack_tuple(v1)
        --local w2 = unpack_tuple(v2)
        --return w1 < w2
        return v1[1] < v2[1]
    end)
    local finished = {}
    q:insertq(make_tuple(srcid, 0))
    while q:count() > 0 do
        local elem = q:remove_top()
        local cur_d, id = unpack_tuple(elem)
        if not finished[id] then
            finished[id] = true
            if id == dstid then
                return cur_d
            end
            local h, w = gethw(id)
            for dh=-2,2 do
                for dw=-2,2 do
                    if isopen(h+dh,w+dw) then
                        local aa = abs(dh)+abs(dw)
                        if aa == 0 then
                            -- 5x5 center
                        else
                            -- move A or B?
                            local step = (aa == 1) and 0 or 1
                            local toid = getid(h+dh,w+dw)
                            if not finished[toid] then
                                -- compare costs
                                local before = from_src[toid] or INF
                                local after = cur_d + step
                                if after < before then
                                    from_src[toid] = after
                                    q:insertq(make_tuple(toid, after))
                                end
                            end
                        end
                    end
                end
            end
        end
    end
    return -1
end

local cost = find_mincost(Ch, Cw, Dh, Dw)
print(cost)


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
--
-- heap
local Heap = {}
function Heap.new(upper_func)
    local self = setmetatable({}, {__index = Heap})
    self.a = {}
    self.upper_func = upper_func
    self.upper = function(k1, k2)
        --assert(k1 < k2)
        if k1 == 0 then
            return false
        else
            return upper_func(self.a[k1], self.a[k2])
        end
    end
    self.lower = function(k1, k2)
        return not self.upper(k1, k2)
    end
    return self
end

function Heap:count()
    return #self.a
end

function Heap:_swap(k1, k2)
    local old_k1 = self.a[k1]
    self.a[k1] = self.a[k2]
    self.a[k2] = old_k1
end

function Heap:upheap(newk)
    local ku = newk // 2
    local k = newk
    while ku > 0 and self.lower(ku, k) do
        self:_swap(ku, k)
        k = k//2
        ku = ku//2
    end
end

function Heap:insertq(e)
    table.insert(self.a, e)
    self:upheap(#self.a)
end

function Heap:downheap(newk)
    local k = newk
    while k <= #self.a//2 do
        local kdl = k*2
        local kdr = kdl + 1
        local kd
        if kdr <= #self.a and self.lower(kdl, kdr) then
            kd = kdr
        else
            kd = kdl
        end
        if self.upper(k, kd) then
            break
        end
        self:_swap(k, kd)
        k = kd
    end
end

function Heap:top()
    assert(#self.a >= 1)
    return self.a[1]
end

function Heap:remove_top()
    --assert(#self.a >= 1)
    local v = self.a[1]
    self:_swap(1, #self.a)
    table.remove(self.a)
    self:downheap(1)
    return v
end

function Heap:replace_top(e)
    assert(#self.a >= 1)
    local old_v = self.a[1]
    local swapped = false
    if self.upper_func(old_v, e) then
        self.a[1] = e
        self:downheap(1)
        swapped = true
    end
    return swapped, old_v
end

--------------------------------------

local K1 = 10000
local K2 = K1 * K1
local INF = math.floor(10^18)
--
local abs = math.abs
--
local H, W = read.nn()
local Ch, Cw = read.nn()
local Dh, Dw = read.nnl()
local S = {}
for i=1,H do
    S[i] = read.l():totable()
end
local function isopen(h, w)
    return S[h] and S[h][w] == '.'
end
local function getid(h, w)
    return w + h * K1
end
local function gethw(id)
    local h, w = id // K1, id % K1
    return h, w
end
local function make_tuple(id, weight)
    return weight * K2 + id
end
local function unpack_tuple(t)
    local weight, id = t // K2, t % K2
    return weight, id
end

-- dijkstra's algorithm
local function find_mincost(srch, srcw, dsth, dstw)
    local srcid = getid(srch, srcw)
    local dstid = getid(dsth, dstw)
    local from_src = {} -- if v is unreachable, from_src[v] == nil.
    from_src[srcid] = 0
    local q = Heap.new(function (v1, v2)
        --local w1 = unpack_tuple(v1)
        --local w2 = unpack_tuple(v2)
        --return w1 < w2
        return v1 // K2 < v2 // K2
    end)
    local finished = {}
    q:insertq(make_tuple(srcid, 0))
    while q:count() > 0 do
        local elem = q:remove_top()
        local cur_d, id = unpack_tuple(elem)
        if not finished[id] then
            finished[id] = true
            if id == dstid then
                return cur_d
            end
            local h, w = gethw(id)
            for dh=-2,2 do
                for dw=-2,2 do
                    if isopen(h+dh,w+dw) then
                        local aa = abs(dh)+abs(dw)
                        if aa == 0 then
                            -- 5x5 center
                        else
                            -- move A or B?
                            local step = (aa == 1) and 0 or 1
                            local toid = getid(h+dh,w+dw)
                            if not finished[toid] then
                                -- compare costs
                                local before = from_src[toid] or INF
                                local after = cur_d + step
                                if after < before then
                                    from_src[toid] = after
                                    q:insertq(make_tuple(toid, after))
                                end
                            end
                        end
                    end
                end
            end
        end
    end
    return -1
end

local cost = find_mincost(Ch, Cw, Dh, Dw)
print(cost)


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)


local S = io.read("l")

local R = string.byte("R")

local max = 0
local count = 0
for i = 1, 3 do
	if S:byte(i) == R then
		count = count + 1
		max = (max < count) and count or max
	else
		count = 0
	end
end

print(max)

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.


a = io.read()
if a == "RRR" then
  print(3)
elseif a:find("RR") then
  print(2)
elseif a:find("R") then
  print(1)
else
  print(0)
end


local read = io.read
local insert = table.insert

local N = read("n")
local L = {}
local L_have_same_num = {}
for i = 1, N do
	local num = read("n")
	if L_have_same_num[num] == nil then
		insert(L, num)
		L_have_same_num[num] = 1
	else
		L_have_same_num[num] = L_have_same_num[num] + 1
	end
end

table.sort(L)

local count = 0
for i = 1, #L - 2 do
	for j = i + 1, #L - 1 do
		for k = j + 1, #L do
			if L[k] >= L[j] + L[i] then
				break
			end
			count = count + L_have_same_num[L[i]] * L_have_same_num[L[j]] * L_have_same_num[L[k]]
		end
	end
end

print(count)

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.


local function reada(n,m)m=m or 1 r={}for i=1,m do r[i]={}end for i=1,n do for j=1,m do r[j][i]=io.read"*n"end end return unpack(r)end
local function istri(a,b,c)
if(a==b or b==c or c==a)then return false end
local max=math.max(a,b,c)
if(max==a)then return a<b+c end
if(max==b)then return b<a+c end
return c<a+b
end
N=io.read"*n"
L=reada(N)
c=0
for i=1,N do
for j=i+1,N do
for k=j+1,N do
if(istri(L[i],L[j],L[k]))then c=c+1 end
end end end
print(c)


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
  print(math.min(math.abs(x - x // d * d - x), math.abs(x - x // d + d + x)))
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) >= k*d 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


local abs = math.abs
local X, K, D = io.read("n", "n", "n")

local abs_X = abs(X)

local K_of_carrent_X = abs_X // D
local carrent_X = abs_X % D
if K <= K_of_carrent_X then
	print(abs(abs_X - K * D))
elseif (K - K_of_carrent_X) % 2 == 0 then
	print(abs(carrent_X))
else
	print(abs(carrent_X - D))
end


local function flag(x)return x>0 and 1 or x<0 and -1 or 0 end
X=io.read"*n"
K=io.read"*n"
D=io.read"*n"

K1=K-math.floor(math.abs(X)/D)
if(K1<0)then print(math.abs(X)-D*K)return end
X=X-flag(X)*D*(K-K1)
print(K1%2==0 and math.abs(X) or D-math.abs(X))


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 X, K, D = read.nnn()
if X < 0 then
    X = -X
end
local a = X // D
local b = X % D
local ans = 10^15
if a < K then
    local r = K - a
    if r % 2 == 0 then
        ans = b
    else
        ans = D - b
    end
elseif a == K then
    ans = b
elseif a > K then
    ans = D * (a - K) + b
end
print(ans)