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 g = {}
for i = 1, n do
  local r = uf_findroot(i)
  g[r] = true
end
local ret = -1
for k, v in pairs(g) do ret = ret + 1 end
print(ret)

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

Score : 300 points

Problem Statement

There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M.
Road i connects City A_i and City B_i.

Snuke can perform the following operation zero or more times:

Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.

After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times).

What is the minimum number of roads he must build to achieve the goal?

Constraints

2 \leq N \leq 100,000

1 \leq M \leq 100,000

1 \leq A_i < B_i \leq N

No two roads connect the same pair of cities.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

Print the answer.

Sample Input 1

3 1
1 2

Sample Output 1

1

Initially, there are three cities, and there is a road between City 1 and City 2.

Snuke can achieve the goal by building one new road, for example, between City 1 and City 3.
After that,

We can travel between 1 and 2 directly.

We can travel between 1 and 3 directly.

We can travel between 2 and 3 by following both roads (2 - 1 - 3).

Submitted source-code file size, in bytes.

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

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


-- Vicfred
-- https://atcoder.jp/contests/abc179/tasks/abc179_a
-- string manipulation

s = io.read()
if s:sub(#s, #s) == "s" then
    print(s .. "es")
else
    print(s .. "s")
end

Score : 100 points

Problem Statement

In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.

In Taknese, the plural form of a noun is spelled based on the following rules:

If a noun's singular form does not end with s, append s to the end of the singular form.

If a noun's singular form ends with s, append es to the end of the singular form.

You are given the singular form S of a Taknese noun. Output its plural form.

Constraints

S is a string of length 1 between 1000, inclusive.

S contains only lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the plural form of the given Taknese word.

Sample Input 1

apple

Sample Output 1

apples

apple ends with e, so its plural form is apples.

Sample Input 2

bus

Sample Output 2

buses

bus ends with s, so its plural form is buses.

Sample Input 3

box

Sample Output 3

boxs


a = io.read()
if a:sub(#a, #a) == "s" then
  print(a .. "es")
else
  print(a .. "s")
end


-- Vicfred
-- https://atcoder.jp/contests/abc179/tasks/abc179_c
-- math, combinatorics
n = io.read("*n")

ans = 0

for a = 1, n-1 do
    ans = ans + (n - 1) // a
end

print(ans)

Score : 300 points

Problem Statement

Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

Constraints

2 \leq N \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

3

Sample Output 1

3

There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).

Sample Input 2

100

Sample Output 2

473

Sample Input 3

1000000

Sample Output 3

13969985


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

a, b, c, d = io.read("*n", "*n", "*n", "*n")

maxima = c*b
maxima = math.max(maxima, d*b)
maxima = math.max(maxima, c*a)
maxima = math.max(maxima, a*d)

print(maxima)

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

local n, q = io.read("*n", "*n")
local fw = FenwickTree.new(n)
for i = 1, n do
  local a = io.read("*n")
  fw:add(i, a)
end
for iq = 1, q do
  local a, b, c = io.read("*n", "*n", "*n")
  if a == 0 then
    fw:add(b + 1, c)
  else
    local ans = fw:sum(c)
    if 0 < b then ans = ans - fw:sum(b) end
    ans = tostring(ans):gsub("LL", "")
    print(ans)
  end
end

Score : 100 points

Problem Statement

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

0 p x: a_p \gets a_p + x

1 l r: Print \sum_{i = l}^{r - 1}{a_i}.

Constraints

1 \leq N, Q \leq 500,000

0 \leq a_i, x \leq 10^9

0 \leq p < N

0 \leq l_i < r_i \leq N

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N Q
a_0 a_1 ... a_{N - 1}
\textrm{Query}_0
\textrm{Query}_1
:
\textrm{Query}_{Q - 1}

Output

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

Sample Input 1

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

Sample Output 1

15
7
25
6


-- 5.3
-- Sum_{i=0}^{n-1} floor{(a * i + b) / b}
local function floorSum(n, m, a, b)
  local ans = 0
  while true do
    if m <= a then
      ans = ans + ((n - 1) * n // 2) * (a // m)
      a = a % m
    end
    if m <= b then
      ans = ans + n * (b // m)
      b = b % m
    end
    local ymax = (a * n + b) // m
    local xmax = ymax * m - b
    if ymax == 0 then break end
    ans = ans + (n - (xmax + a - 1) // a) * ymax
    n, m, a, b = ymax, a, m, (a - xmax % a) % a
  end
  return ans
end

local q = io.read("*n")
for i = 1, q do
  local n, m, a, b = io.read("*n", "*n", "*n", "*n")
  print(floorSum(n, m, a, b))
end

Score : 100 points

Problem Statement

In this problem, you should process T testcases.

For each testcase, you are given four integers N, M, A, B.

Calculate \sum_{i = 0}^{N - 1} floor((A \times i + B) / M).

Constraints

1 \leq T \leq 100,000

1 \leq N, M \leq 10^9

0 \leq A, B < M

Input

Input is given from Standard Input in the following format:

T
N_0 M_0 A_0 B_0
N_1 M_1 A_1 B_1
:
N_{T - 1} M_{T - 1} A_{T - 1} B_{T - 1}

Output

Print the answer for each testcase.

Sample Input 1

5
4 10 6 3
6 5 4 3
1 1 0 0
31415 92653 58979 32384
1000000000 1000000000 999999999 999999999

Sample Output 1

3
13
0
314095480
499999999500000000


--[[------------------------------------------------------------------------]]--
local function floor_sum(elm_num, div_num, mul_num, add_num)
	local ans = 0
	if mul_num >= div_num then
		ans = ans + (elm_num - 1) * elm_num * (mul_num // div_num) // 2
		mul_num = mul_num % div_num
	end
	if add_num >= div_num then
		ans = ans + elm_num * (add_num // div_num)
		add_num = add_num % div_num
	end

	local y_max = (mul_num * elm_num + add_num) // div_num
	local x_max = (y_max * div_num - add_num)
	if y_max == 0 then
		return ans
	else
		ans = ans + (elm_num - (x_max + mul_num - 1) // mul_num) * y_max
		ans = ans + floor_sum(
			y_max, mul_num, div_num,
			(mul_num - x_max % mul_num) % mul_num, ans
		)
		return ans
	end
end
--[[------------------------------------------------------------------------]]--

local read = io.read
local t = read("n")

local out_t = {}
for i = 1, t do
	out_t[i] = floor_sum(read("n", "n", "n", "n"))
end
print(table.concat(out_t, "\n"))


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.walkDK = function(self)
  -- Dijkstra-like walk
  local edge_dst, edge_cost, edge_cap = self.edge_dst, self.edge_cost, self.edge_cap
  local len = self.len
  local taskstate = {}
  local tasks = {}
  local tasknum, done = 0, 0
  local tasklim = self.n
  for i = 1, tasklim do taskstate[i] = false end
  local function addtask(idx)
    if not taskstate[idx] then
      taskstate[idx] = true
      tasknum = tasknum + 1
      local taskidx = tasknum % tasklim
      if taskidx == 0 then taskidx = tasklim end
      tasks[taskidx] = idx
    end
  end
  local function walk(src, dst, cost)
    if len[src] + cost < len[dst] then
      len[dst] = len[src] + cost
      addtask(dst)
    end
  end
  addtask(self.spos)
  while done < tasknum do
    done = done + 1
    local taskidx = done % tasklim
    if taskidx == 0 then taskidx = tasklim end
    local idx = tasks[taskidx]
    taskstate[idx] = false
    local eddst, edcap, edcost = edge_dst[idx], edge_cap[idx], edge_cost[idx]
    for i = 1, #eddst do
      if 0 < edcap[i] then
        walk(idx, eddst[i], edcost[i])
      end
    end
  end
end
MinCostFlow.walkBF = function(self)
  --Bellman-Ford walk
  local edge_dst, edge_cost, edge_cap = self.edge_dst, self.edge_cost, self.edge_cap
  local len = self.len
  local n = self.n
  local updated1, updated2 = {}, {}
  for i = 1, n do
    updated1[i] = true
  end
  len[self.spos] = 0
  for irp = 1, n do
    local updsrc = irp % 2 == 1 and updated1 or updated2
    local upddst = irp % 2 == 1 and updated2 or updated1
    for i = 1, n do
      upddst[i] = false
    end
    for src = 1, n do
      if updsrc[src] then
        local eddst, edcap, edcost = edge_dst[src], edge_cap[src], edge_cost[src]
        for i = 1, #eddst do
          if 0 < edcap[i] then
            local dst = eddst[i]
            local cost = edcost[i]
            if len[src] + cost < len[dst] then
              len[dst] = len[src] + cost
              upddst[dst] = true
            end
          end
        end
      end
    end
  end
end

MinCostFlow.makeSubGraph = function(self)
  local inf = self.inf
  local len = self.len
  local n = self.n
  local edge_dst, edge_cap = self.edge_dst, self.edge_cap
  local edge_dst_invedge_idx = self.edge_dst_invedge_idx
  local edge_cost = self.edge_cost
  local sub_graph_v = self.sub_graph_v
  local sub_graph_edgeidx = self.sub_graph_edgeidx
  local sub_graph_flag = self.sub_graph_flag
  for i = 1, n do
    len[i] = inf
    sub_graph_flag[i] = false
  end
  len[self.spos] = 0

  -- Bellman-Ford is good, but Dijkstra-like is very fast in some case
  self:walkDK()
  -- self:walkBF()

  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 mab = math.abs
local n, d = io.read("*n", "*n")
local edge = {}
local edge_asked = {}
local invedge = {}
local invedge_asked = {}
for i = 1, 2 * n do
  edge[i] = {}
  edge_asked[i] = 0
  invedge[i] = {}
  invedge_asked[i] = 0
end
local edgeinfo = {}
local xs, ys = {}, {}
for i = 1, n do
  xs[i], ys[i] = io.read("*n", "*n")
end
local function addedge(src, dst)
  table.insert(edgeinfo, {src, dst})
  table.insert(edge[src], dst)
  table.insert(invedge[dst], src)
end
for i = 1, n - 1 do
  for j = i + 1, n do
    f1 = mab(xs[i] - xs[j]) < d
    f2 = mab(xs[i] - ys[j]) < d
    f3 = mab(ys[i] - xs[j]) < d
    f4 = mab(ys[i] - ys[j]) < d
    if f1 and not f2 then addedge(i, n + j) end
    if f2 and not f1 then addedge(i, j) end
    if f3 and not f4 then addedge(n + i, n + j) end
    if f4 and not f3 then addedge(n + i, j) end
    if f1 and not f3 then addedge(j, n + i) end
    if f3 and not f1 then addedge(j, i) end
    if f2 and not f4 then addedge(n + j, n + i) end
    if f4 and not f2 then addedge(n + j, i) end

    if f1 and f2 then addedge(i, n + i) end
    if f3 and f4 then addedge(n + i, i) end
    if f1 and f3 then addedge(j, n + j) end
    if f2 and f4 then addedge(n + j, j) end
  end
end
local rawn = n
n = n * 2

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

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

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

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

local gsize = {}
local gedge, ginvedge = {}, {}
local glen = {}
local gmember = {}

local function SCCD_make_group_graph()
  for i = 1, n do
    gsize[i] = 0
    gedge[i], ginvedge[i] = {}, {}
    glen[i] = 0
    gmember[i] = {}
  end
  for i = 1, n do
    local r = sccd_root[i]
    gsize[r] = gsize[r] + 1
    table.insert(gmember[r], i)
  end
  for i = 1, #edgeinfo do
    local a, b = edgeinfo[i][1], edgeinfo[i][2]
    local ra, rb = sccd_root[a], sccd_root[b]
    if ra ~= rb then
      table.insert(gedge[ra], rb)
      table.insert(ginvedge[rb], ra)
    end
  end
end

local function SCCD_toposort()
  local topo_tasks = {}
  local topo_asked_cnt = {}
  for i = 1, n do
    topo_asked_cnt[i] = 0
    if 0 < gsize[i] and #ginvedge[i] == 0 then
      table.insert(topo_tasks, i)
    end
  end
  local topoary = {}
  local topo_done = 0
  while topo_done < #topo_tasks do
    topo_done = topo_done + 1
    local g = topo_tasks[topo_done]
    topoary[topo_done] = g
    for i = 1, #gedge[g] do
      local dst = gedge[g][i]
      topo_asked_cnt[dst] = topo_asked_cnt[dst] + 1
      if topo_asked_cnt[dst] == #ginvedge[dst] then
        table.insert(topo_tasks, dst)
      end
    end
  end
  return topoary
end

SCCD_categorize()
SCCD_make_group_graph()

for i = 1, rawn do
  if sccd_root[i] == sccd_root[i + rawn] then
    print("No") os.exit()
  end
end
print("Yes")
local determined = {}
local retpos = {}
for i = 1, rawn do
  determined[i] = false
  retpos[i] = -1
end

local topoary = SCCD_toposort()
for i = 1, #topoary do
  local g = topoary[i]
  for j = 1, #gmember[g] do
    local idx = gmember[g][j]
    if idx <= rawn then
      if not determined[idx] then
        retpos[idx] = ys[idx]
        determined[idx] = true
      end
    else
      if not determined[idx - rawn] then
        retpos[idx - rawn] = xs[idx - rawn]
        determined[idx - rawn] = true
      end
    end
  end
end
print(table.concat(retpos, "\n"))

Score : 100 points

Problem Statement

Consider placing N flags on a line. Flags are numbered through 1 to N.

Flag i can be placed on the coordinate X_i or Y_i.
For any two different flags, the distance between them should be at least D.

Decide whether it is possible to place all N flags. If it is possible, print such a configulation.

Constraints

1 \leq N \leq 1000

0 \leq D \leq 10^9

0 \leq X_i < Y_i \leq 10^9

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N

Output

Print No if it is impossible to place N flags.

If it is possible, print Yes first.
After that, print N lines. i-th line of them should contain the coodinate of flag i.

Sample Input 1

3 2
1 4
2 5
0 6

Sample Output 1

Yes
4
2
0

Sample Input 2

3 3
1 4
2 5
0 6

Sample Output 2

No


--[[------------------------------------------------------------------------]]--
--- `0 <= num <= 1<<61` 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

--- index >= 1
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
		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
	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])を、
--- モノイドの性質を満たしていると仮定して計算します。l = r のときはe()を返します。
--- O(log(n))
function SegTree:prod(left, right)
	assert(1 <= left and left <= right and right <= self._.vec_len)
	local vec = self._.vec
	local operation_fn = self._.operation_fn

	local operated_left = self._.init_val_fn()
	local operated_right = self._.init_val_fn()
	left = left - 1 + self._.len
	right = right - 1 + self._.len
	while left < right do
		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:all_prod()
	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:max_right(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の値が入ります。
--- segtreeの上で二分探索をします。
--- 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
		right = right - 1
		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 - len
		end
		value = operation_fn(vec[right], value)

		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:prod(l_i, r_i))
	else
		local x_i, v_i = read("n", "n")
		insert(
			out_t,
			segTree:max_right(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 d,t,s=io.read("n","n","n")
print(s*t>=d and "Yes" or "No")

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

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

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

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

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

Sample Input 1

1000 15 80

Sample Output 1

Yes

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

Sample Input 2

2000 20 100

Sample Output 2

Yes

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

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


local s=io.read()
local t=io.read()
local min=math.maxinteger
for i=1,#s-#t+1 do
    local ss=s:sub(i,i+#t-1)
    local counter=0
    for j=1,#t do
        if ss:byte(j)~=t:byte(j) then
            counter=counter+1
        end
    end
    min=math.min(counter,min)
end
print(min)

Score : 200 points

Problem Statement

Given are two strings S and T.

Let us change some of the characters in S so that T will be a substring of S.

At least how many characters do we need to change?

Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.

Constraints

The lengths of S and T are each at least 1 and at most 1000.

The length of T is at most that of S.

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the minimum number of characters in S that need to be changed.

Sample Input 1

cabacc
abc

Sample Output 1

1

For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.

Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.

Sample Input 2

codeforces
atcoder

Sample Output 2

6


local mmi, mma = math.min, math.max
local h, w = io.read("*n", "*n")
local a, b = {}, {}
for i = 1, h do
  a[i], b[i] = io.read("*n", "*n")
end

local inf = 1000000007
local ret = {}
for i = 1, h do
  ret[i] = inf
end
local task_l, task_r, task_len, task_d = {}, {}, {}, {}
local function addtask(left, right, curlen, deg)
  ret[deg] = mmi(ret[deg], curlen)
  table.insert(task_l, left)
  table.insert(task_r, right)
  table.insert(task_len, curlen)
  table.insert(task_d, deg)
end
local function addtask_start(left, right, curlen, deg)
  table.insert(task_l, left)
  table.insert(task_r, right)
  table.insert(task_len, curlen)
  table.insert(task_d, deg)
end

local function solve(left, right, curlen, deg)
  deg = deg + 1
  if h < deg then return end
  curlen = curlen + 1
  if a[deg] <= left and right <= b[deg] then
    if b[deg] == w then return end
    curlen = curlen + b[deg] + 1 - right
    addtask(b[deg] + 1, b[deg] + 1, curlen, deg)
  elseif right < a[deg] or b[deg] < left then
    addtask(left, right, curlen, deg)
  else
    if b[deg] < right then
      addtask(b[deg] + 1, right, curlen, deg)
    elseif b[deg] < w then
      curlen = curlen + b[deg] + 1 - right
      addtask(b[deg] + 1, b[deg] + 1, curlen, deg)
    end
    if left < a[deg] then
      addtask(left, a[deg] - 1, curlen, deg)
    end
  end
end
addtask_start(1, w, 0, 0)
while 0 < #task_l do
  local left = task_l[#task_l]
  table.remove(task_l)
  local right = task_r[#task_r]
  table.remove(task_r)
  local curlen = task_len[#task_len]
  table.remove(task_len)
  local deg = task_d[#task_d]
  table.remove(task_d)
  solve(left, right, curlen, deg)
end
for i = 1, h do
  if ret[i] == inf then ret[i] = -1 end
end
print(table.concat(ret, "\n"))

Score : 600 points

Problem Statement

There is a grid of squares with H+1 horizontal rows and W vertical columns.

You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top.

For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print -1 instead.

Constraints

1 \leq H,W \leq 2\times 10^5

1 \leq A_i \leq B_i \leq W

Input

Input is given from Standard Input in the following format:

H W
A_1 B_1
A_2 B_2
:
A_H B_H

Output

Print H lines. The i-th line should contain the answer for the case k=i.

Sample Input 1

4 4
2 4
1 1
2 3
2 4

Sample Output 1

1
3
6
-1

Let (i,j) denote the square at the i-th row from the top and j-th column from the left.

For k=1, we need one move such as (1,1) → (2,1).

For k=2, we need three moves such as (1,1) → (2,1) → (2,2) → (3,2).

For k=3, we need six moves such as (1,1) → (2,1) → (2,2) → (3,2) → (3,3) → (3,4) → (4,4).

For k=4, it is impossible to reach any square in the fifth row from the top.


local mmi, mma = math.min, math.max
local h, w = io.read("*n", "*n")
local a, b = {}, {}
for i = 1, h do
  a[i], b[i] = io.read("*n", "*n")
end
if a[1] == 1 and b[1] == w then
  for i = 1, h do
    print(-1)
  end
  os.exit()
end

local asked_by_depth = {}
for i = 1, h do
  asked_by_depth[i] = {}
end
local inf = 1000000007
local ret = {}
for i = 1, h + 1 do
  ret[i] = inf
end
local function solve(spos)
  local th = h
  local curpos = spos
  local t = {curpos}
  for i = 1, h do
    if curpos < a[i] or b[i] < curpos then
    else
      if b[i] == w then
        th = i - 1 break
      end
      curpos = b[i] + 1
    end
    t[i + 1] = curpos
  end
  -- print(th, table.concat(t, " "))
  for i = th, 1, -1 do
    if curpos < a[i] or b[i] < curpos then
    else
      curpos = a[i] - 1
    end
  end
  spos = curpos
  for i = 1, th do
    if curpos < a[i] or b[i] < curpos then
    else
      curpos = b[i] + 1
    end
    ret[i] = mmi(ret[i], i + curpos - spos)
  end
end

if 1 < a[1] then
  solve(1)
end
if b[1] < w then
  solve(b[1] + 1)
end
for i = 1, h do
  if ret[i] == inf then ret[i] = -1 end
end
ret[h + 1] = nil
print(table.concat(ret, "\n"))


local n, x, t = io.read("n", "n", "n")

print((n % x ==0) and n // x * t or n // x * t + t)

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("n")
local prev=io.read("n")
local total=0
for i=2,n do
    local cur=io.read("n")
    total=total+(prev>cur and prev-cur or 0)
    prev=(prev>cur and prev or cur)
end
print(total)

Score : 300 points

Problem Statement

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

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

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

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

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

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

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

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

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

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


local n=io.read("n")
local prev=io.read("n")
local total=0
for i=2,n do
    local cur=io.read("n")
    total=total+(prev>cur and prev-cur or 0)
    prev=cur
end
print(total)


local n=io.read("n")
local prev=io.read("n")
local total=0
for i=2,n do
    local cur=io.read("n")
    total=total+(prev-cur)
    prev=cur
end
print(total)


local mfl, mce = math.floor, math.ceil
local mmi, mma = math.min, math.max
local pow2 = {1}
for i = 2, 28 do pow2[i] = pow2[i - 1] * 2 end
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    local cnt = pow2[i]
    for j = 0, cnt - 1 do
      self.stage[cnt + j] = self.func(self.stage[(cnt + j) * 2], self.stage[(cnt + j) * 2 + 1])
    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
  end
  self.stagenum = stagenum
  for i = 1, mul * 2 - 1 do self.stage[i] = emptyvalue end
  for i = 1, n do self.stage[mul + i - 1] = i end
  self:updateAll()
end
SegTree.update = function(self, idx)
  idx = idx + pow2[self.stagenum] - 1
  for i = self.stagenum - 1, 1, -1 do
    local dst = mfl(idx / 2)
    local rem = dst * 4 + 1 - idx
    self.stage[dst] = self.func(self.stage[idx], self.stage[rem])
    idx = dst
  end
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local h, w = io.read("*n", "*n", "*l")
local sh, sw = io.read("*n", "*n", "*l")
local th, tw = io.read("*n", "*n", "*l")
local dot = string.byte(".")
local map = {}
local len = {}
local asked = {}
local inf = 1000000007
for i = 1, h do
  local s = io.read()
  for j = 1, w do
    local idx = (i - 1) * w + j
    map[idx] = s:byte(j) == dot
    len[idx] = inf
    asked[idx] = false
  end
end
local n = h * w
asked[n + 1] = true
len[(sh - 1) * w + sw] = 0

local function mergefunc(x, y)
  if asked[x] then return y
  elseif asked[y] then return x
  else
    return len[x] < len[y] and x or y
  end
end

local st = SegTree.new(n, mergefunc, n + 1)

local function walk(src, dst, cost)
  if map[dst] then
    if len[src] + cost < len[dst] then
      len[dst] = len[src] + cost
      st:update(dst)
    end
  end
end

for i = 1, n do
  local src = st.stage[1]
  if asked[src] then break end
  asked[src] = true
  st:update(src)
  local src_h = mce(src / w)
  local src_w = src - (src_h - 1) * w
  do
    if 2 < src_h then walk(src, src - 2 * w, 1) end
    if 1 < src_h then walk(src, src - w, 0) end
    if src_h < h then walk(src, src + w, 0) end
    if src_h < h - 1 then walk(src, src + 2 * w, 1) end
  end
  if 1 < src_w then
    walk(src, src - 1, 0)
    if 2 < src_h then walk(src, src - 1 - 2 * w, 1) end
    if 1 < src_h then walk(src, src - 1 - w, 1) end
    if src_h < h then walk(src, src - 1 + w, 1) end
    if src_h < h - 1 then walk(src, src - 1 + 2 * w, 1) end
  end
  if src_w < w then
    walk(src, src + 1, 0)
    if 2 < src_h then walk(src, src + 1 - 2 * w, 1) end
    if 1 < src_h then walk(src, src + 1 - w, 1) end
    if src_h < h then walk(src, src + 1 + w, 1) end
    if src_h < h - 1 then walk(src, src + 1 + 2 * w, 1) end
  end
  if 2 < src_w then
    walk(src, src - 2, 1)
    if 2 < src_h then walk(src, src - 2 - 2 * w, 1) end
    if 1 < src_h then walk(src, src - 2 - w, 1) end
    if src_h < h then walk(src, src - 2 + w, 1) end
    if src_h < h - 1 then walk(src, src - 2 + 2 * w, 1) end
  end
  if src_w < w - 1 then
    walk(src, src + 2, 1)
    if 2 < src_h then walk(src, src + 2 - 2 * w, 1) end
    if 1 < src_h then walk(src, src + 2 - w, 1) end
    if src_h < h then walk(src, src + 2 + w, 1) end
    if src_h < h - 1 then walk(src, src + 2 + 2 * w, 1) end
  end
end

local ret = len[(th - 1) * w + tw]
print(ret < inf and ret 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 mfl, mce = math.floor, math.ceil
local mmi, mma = math.min, math.max
local pow2 = {1}
for i = 2, 28 do pow2[i] = pow2[i - 1] * 2 end
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    local cnt = pow2[i]
    for j = 0, cnt - 1 do
      self.stage[cnt + j] = self.func(self.stage[(cnt + j) * 2], self.stage[(cnt + j) * 2 + 1])
    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
  end
  self.stagenum = stagenum
  for i = 1, mul * 2 - 1 do self.stage[i] = emptyvalue end
  for i = 1, n do self.stage[mul + i - 1] = i end
  self:updateAll()
end
SegTree.update = function(self, idx)
  idx = idx + pow2[self.stagenum] - 1
  for i = self.stagenum - 1, 1, -1 do
    local dst = mfl(idx / 2)
    local rem = dst * 4 + 1 - idx
    self.stage[dst] = self.func(self.stage[idx], self.stage[rem])
    idx = dst
  end
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local h, w = io.read("*n", "*n", "*l")
local sh, sw = io.read("*n", "*n", "*l")
local th, tw = io.read("*n", "*n", "*l")
local dot = string.byte(".")
local map = {}
local len = {}
local asked = {}
local inf = 1000000007
for i = 1, h do
  local s = io.read()
  for j = 1, w do
    local idx = (i - 1) * w + j
    map[idx] = s:byte(j) == dot
    len[idx] = inf
    asked[idx] = false
  end
end
local n = h * w
asked[n + 1] = true
len[(sh - 1) * w + sw] = 0

local function mergefunc(x, y)
  if asked[x] then return y
  elseif asked[y] then return x
  else
    return len[x] < len[y] and x or y
  end
end

local st = SegTree.new(n, mergefunc, n + 1)

local function walk(src, dst, cost)
  if map[dst] then
    if len[src] + cost < len[dst] then
      len[dst] = len[src] + cost
      st:update(dst)
    end
  end
end

for i = 1, n do
  local src = st.stage[1]
  if asked[src] then break end
  asked[src] = true
  st:update(src)
  local src_h = mce(src / w)
  local src_w = src - (src_h - 1) * w
  do
    if 2 < src_h then walk(src, src - 2 * w, 1) end
    if 1 < src_h then walk(src, src - w, 0) end
    if src_h < h then walk(src, src + w, 0) end
    if src_h < h - 1 then walk(src, src + 2 * w, 1) end
  end
  if 1 < src_w then
    walk(src, src - 1, 0)
    if 2 < src_h then walk(src, src - 1 - 2 * w, 1) end
    if 1 < src_h then walk(src, src - 1 - w, 1) end
    if src_h < h then walk(src, src - 1 + w, 1) end
    if src_h < h - 1 then walk(src, src - 1 + 2 * w, 1) end
  end
  if src_w < w then
    walk(src, src + 1, 0)
    if 2 < src_h then walk(src, src + 1 - 2 * w, 1) end
    if 1 < src_h then walk(src, src + 1 - w, 1) end
    if src_h < h then walk(src, src + 1 + w, 1) end
    if src_h < h - 1 then walk(src, src - 1 + 2 * w, 1) end
  end
  if 2 < src_w then
    walk(src, src - 2, 1)
    if 2 < src_h then walk(src, src - 2 - 2 * w, 1) end
    if 1 < src_h then walk(src, src - 2 - w, 1) end
    if src_h < h then walk(src, src - 2 + w, 1) end
    if src_h < h - 1 then walk(src, src - 2 + 2 * w, 1) end
  end
  if src_w < w - 1 then
    walk(src, src + 2, 1)
    if 2 < src_h then walk(src, src + 2 - 2 * w, 1) end
    if 1 < src_h then walk(src, src + 2 - w, 1) end
    if src_h < h then walk(src, src + 2 + w, 1) end
    if src_h < h - 1 then walk(src, src + 2 + 2 * w, 1) end
  end
end

local ret = len[(th - 1) * w + tw]
print(ret < inf and ret or -1)


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=10^13
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 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 H, W, M = read.nnn()
local RT = {}
for i=1,H do RT[i] = {0,i} end
local CT = {}
for i=1,W do CT[i] = {0,i} end
local T = array(2)
for i=1,M do
    local h, w = read.nn()
    T[h][w] = 1
    RT[h][1] = RT[h][1] + 1
    CT[w][1] = CT[w][1] + 1
end
table.sort(RT, function(x, y)
    return x[1] > y[1]
end)
table.sort(CT, function(x, y)
    return x[1] > y[1]
end)

local function count(ri, ci)
    local c = RT[ri][1] + CT[ci][1]
    local bh, bw = RT[ri][2], CT[ci][2]
    if T[bh][bw] then
        return c - 1, true
    else
        return c, false
    end
end
local ans = -1
local hmax = -1
local wmax = -1
for ri=1,H do
    local rt = RT[ri][1]
    if rt > hmax then
        hmax = rt
    elseif rt < hmax then
        break
    end
    for ci=1,W do
        local ct = CT[ci][1]
        if ct > wmax then
            wmax = ct
        elseif ct < wmax then
            break
        end
        local a, dup = count(ri, ci)
        if not dup then
            print(a)
            os.exit()
        end
        ans = math.max(a, ans)
    end
end
print(ans)


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
local function array(dimensi0n, default_val) assert(type(default_val) ~= 'table') local n=dimensi0n local m={}if default_val~=nil then m[1]={__index=function()return default_val end}end for i=2,n do m[i]={__index=function(p, k)local c=setmetatable({},m[i-1])rawset(p,k,c)return c end}end return setmetatable({},m[n])end
--
local S = read.l()
if S == 'SSS' then
    print(0)
elseif S == 'RSS' or S == 'SRS' or S == 'SSR' or S == 'RSR' then
    print(1)
else
    print(2)
end

Score : 100 points

Problem Statement

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

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

Constraints

|S| = 3

Each character of S is S or R.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

RRS

Sample Output 1

2

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

Sample Input 2

SSS

Sample Output 2

0

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

Sample Input 3

RSR

Sample Output 3

1

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


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

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

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.


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

Score : 400 points

Problem Statement

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

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

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

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

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

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

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

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

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

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

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

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

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

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


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


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

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

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

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

Score : 500 points

Problem Statement

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

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

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

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

Constraints

1 \leq R, C \leq 3000

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

1 \leq r_i \leq R

1 \leq c_i \leq C

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

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

8

He has two ways to get to the goal:

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

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

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

Sample Input 2

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

Sample Output 2

29

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

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

Sample Input 3

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

Sample Output 3

142


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

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

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

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


io.read(x)
if(x>=30)then
  print("Yes")
else
  print("No")
end

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


N=io.read"*n"
D=io.read"*n"
X,Y={},{}
for i=1,N do
X[i]=io.read"*n"
Y[i]=io.read"*n"
end
c=0

for i=1,N do
	if(X[i]*X[i]+Y[i]*Y[i]<=D*D)then c=c+1 end
end

print(c)

Score : 200 points

Problem Statement

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

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

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

|X_i|,|Y_i| \leq 2\times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

\sqrt{0^2+5^2}=5

\sqrt{(-2)^2+4^2}=4.472\ldots

\sqrt{3^2+4^2}=5

\sqrt{4^2+(-4)^2}=5.656\ldots

Thus, we have three points such that the distance from the origin is at most 5.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6


k = io.read("*n")

if k % 2 == 0 then
  print(-1)
  return
end

sevens = 7
step = 1

while sevens % k ~= 0 do
  if step > 10 ^ 6 then
    step = -1
    break
  end

  sevens = sevens * 10 + 7
  sevens = sevens % k
  step = step + 1
end

print(step)

Score : 300 points

Problem Statement

Takahashi loves the number 7 and multiples of K.

Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)

If the sequence contains no multiples of K, print -1 instead.

Constraints

1 \leq K \leq 10^6

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print an integer representing the position of the first occurrence of a multiple of K. (For example, if the first occurrence is the fourth element of the sequence, print 4.)

Sample Input 1

101

Sample Output 1

4

None of 7, 77, and 777 is a multiple of 101, but 7777 is.

Sample Input 2

2

Sample Output 2

-1

All elements in the sequence are odd numbers; there are no multiples of 2.

Sample Input 3

999983

Sample Output 3

999982


local n=io.read("n","l")
local s=io.read()

local _,red=s:gsub("R","")
for i=1,red do
    if s:sub(i,i)=="R" then
        red=red-1
    end
end
print(red)

Score : 400 points

Problem Statement

An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; R stands for red and W stands for white.

You can do the following two kinds of operations any number of times in any order:

Choose two stones (not necessarily adjacent) and swap them.

Choose one stone and change its color (from red to white and vice versa).

According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

Constraints

2 \leq N \leq 200000

c_i is R or W.

Input

Input is given from Standard Input in the following format:

N
c_{1}c_{2}...c_{N}

Output

Print an integer representing the minimum number of operations needed.

Sample Input 1

4
WWRR

Sample Output 1

2

For example, the two operations below will achieve the objective.

Swap the 1-st and 3-rd stones from the left, resulting in RWWR.

Change the color of the 4-th stone from the left, resulting in RWWW.

Sample Input 2

2
RR

Sample Output 2

0

It can be the case that no operation is needed.

Sample Input 3

8
WRWWRWRR

Sample Output 3

3


local mmi, mma = math.min, math.max
local mfl, mce = math.floor, math.ceil
local n, k = io.read("*n", "*n")
local t = {}
for i = 1, n do
  t[i] = io.read("*n")
end
local function solve(x)
  local c = 0
  for i = 1, n do
    c = c + mma(0, mce(t[i] / x) - 1)
  end
  return c <= k
end
local min, max = 0, 1000000000
while 1 < max - min do
  local mid = mfl((min + max) / 2)
  if solve(mid) then
    max = mid
  else
    min = mid
  end
end
print(max)

Score : 500 points

Problem Statement

We have N logs of lengths A_1,A_2,\cdots A_N.

We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.

Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.

Constraints

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

0 \leq K \leq 10^9

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print an integer representing the answer.

Sample Input 1

2 3
7 9

Sample Output 1

4

First, we will cut the log of length 7 at a point whose distance from an end of the log is 3.5, resulting in two logs of length 3.5 each.

Next, we will cut the log of length 9 at a point whose distance from an end of the log is 3, resulting in two logs of length 3 and 6.

Lastly, we will cut the log of length 6 at a point whose distance from an end of the log is 3.3, resulting in two logs of length 3.3 and 2.7.

In this case, the longest length of a log will be 3.5, which is the shortest possible result. After rounding up to an integer, the output should be 4.

Sample Input 2

3 0
3 4 5

Sample Output 2

5

Sample Input 3

10 10
158260522 877914575 602436426 24979445 861648772 623690081 433933447 476190629 262703497 211047202

Sample Output 3

292638192


local X = io.read("*n")

local div_x = math.floor(X / 200)
print(10 - div_x)

Score: 100 points

Problem Statement

M-kun is a competitor in AtCoder, whose highest rating is X.

In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:

From 400 through 599: 8-kyu

From 600 through 799: 7-kyu

From 800 through 999: 6-kyu

From 1000 through 1199: 5-kyu

From 1200 through 1399: 4-kyu

From 1400 through 1599: 3-kyu

From 1600 through 1799: 2-kyu

From 1800 through 1999: 1-kyu

What kyu does M-kun have?

Constraints

400 \leq X \leq 1999

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the kyu M-kun has, as an integer.
For example, if he has 8-kyu, print 8.

Sample Input 1

725

Sample Output 1

7

M-kun's highest rating is 725, which corresponds to 7-kyu.

Thus, 7 is the correct output.

Sample Input 2

1600

Sample Output 2

2

M-kun's highest rating is 1600, which corresponds to 2-kyu.

Thus, 2 is the correct output.


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 N, K = read.nn()
local A = read.N(N)
for i=K+1,N do
    local n, o = A[i], A[i-K]
    if n > o then
        print("Yes")
    else
        print("No")
    end
end

Score: 300 points

Problem Statement

M-kun is a student in Aoki High School, where a year is divided into N terms.

There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:

For the first through (K-1)-th terms: not given.

For each of the K-th through N-th terms: the multiplication of the scores in the last K exams, including the exam in the graded term.

M-kun scored A_i in the exam at the end of the i-th term.

For each i such that K+1 \leq i \leq N, determine whether his grade for the i-th term is strictly greater than the grade for the (i-1)-th term.

Constraints

2 \leq N \leq 200000

1 \leq K \leq N-1

1 \leq A_i \leq 10^{9}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 A_3 \ldots A_N

Output

Print the answer in N-K lines.

The i-th line should contain Yes if the grade for the (K+i)-th term is greater than the grade for the (K+i-1)-th term, and No otherwise.

Sample Input 1

5 3
96 98 95 100 20

Sample Output 1

Yes
No

His grade for each term is computed as follows:

3-rd term: (96 \times 98 \times 95) = 893760

4-th term: (98 \times 95 \times 100) = 931000

5-th term: (95 \times 100 \times 20) = 190000

Sample Input 2

3 2
1001 869120 1001

Sample Output 2

No

Note that the output should be No if the grade for the 3-rd term is equal to the grade for the 2-nd term.

Sample Input 3

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

Sample Output 3

Yes
Yes
No
Yes
Yes
No
Yes
Yes


local n, k = io.read("*n", "*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
for i = k + 1, n do
  if a[i - k] < a[i] then
    print("Yes")
  else
    print("No")
  end
end


local n=io.read("n")
local a={}
for i=1,n do
    a[i]=io.read("n")
end
local motode=1000
for i=1,n-1 do
    if a[i]<a[i+1] then
        local torihiki=motode//a[i]
        motode=motode+(a[i+1]-a[i])*torihiki
    end
end
print(motode)

Score: 400 points

Problem Statement

To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives.

He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the next N days will be as follows:

A_1 yen on the 1-st day, A_2 yen on the 2-nd day, ..., A_N yen on the N-th day.

In the i-th day, M-kun can make the following trade any number of times (possibly zero), within the amount of money and stocks that he has at the time.

Buy stock: Pay A_i yen and receive one stock.

Sell stock: Sell one stock for A_i yen.

What is the maximum possible amount of money that M-kun can have in the end by trading optimally?

Constraints

2 \leq N \leq 80

100 \leq A_i \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the maximum possible amount of money that M-kun can have in the end, as an integer.

Sample Input 1

7
100 130 130 130 115 115 150

Sample Output 1

1685

In this sample input, M-kun has seven days of trading. One way to have 1685 yen in the end is as follows:

Initially, he has 1000 yen and no stocks.

Day 1: Buy 10 stocks for 1000 yen. Now he has 0 yen.

Day 2: Sell 7 stocks for 910 yen. Now he has 910 yen.

Day 3: Sell 3 stocks for 390 yen. Now he has 1300 yen.

Day 4: Do nothing.

Day 5: Buy 1 stock for 115 yen. Now he has 1185 yen.

Day 6: Buy 10 stocks for 1150 yen. Now he has 35 yen.

Day 7: Sell 11 stocks for 1650 yen. Now he has 1685 yen.

There is no way to have 1686 yen or more in the end, so the answer is 1685.

Sample Input 2

6
200 180 160 140 120 100

Sample Output 2

1000

In this sample input, it is optimal to do nothing throughout the six days, after which we will have 1000 yen.

Sample Input 3

2
157 193

Sample Output 3

1216

In this sample input, it is optimal to buy 6 stocks in Day 1 and sell them in Day 2, after which we will have 1216 yen.


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

local n = io.read("*n")
local x, y, p = {}, {}, {}
local flag = {}
for i = 1, n do
  x[i], y[i], p[i] = io.read("*n", "*n", "*n")
end

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

local function getmincosts(ik, pos, val, idx_pos, idx_val)
  local retary = {}
  for i = 1, ik + 1 do retary[i] = 0 end
  for i = 1, #pos do flag[i] = false end
  local targetpos = {}
  for linecnt = 0, ik do
    if #pos <= linecnt then
      break
    end
    if 0 < linecnt then
      flag[idx_val[linecnt]] = true
      table.insert(targetpos, pos[idx_val[linecnt]])
    end
    local retval = 0
    for i = 1, #idx_pos do
      local idx_i = idx_pos[i]
      if not flag[idx_i] then
        local p = pos[idx_i]
        local cand = mab(p)
        for j = 1, #targetpos do
          cand = mmi(cand, mab(targetpos[j] - p))
        end
        retval = retval + cand * val[idx_i]
      end
    end
    retary[linecnt + 1] = retval
  end
  return retary
end

local retik = {}

local xs, ys = {}, {}
local function add_func(idx)
  local xv = x[idx]
  local yv = y[idx]
  xs[xv] = xs[xv] - p[idx]
  if xs[xv] == 0 then xs[xv] = nil end
  if not ys[yv] then
    ys[yv] = p[idx]
  else
    ys[yv] = ys[yv] + p[idx]
  end
end
local function rm_func(idx)
  local xv = x[idx]
  local yv = y[idx]
  ys[yv] = ys[yv] - p[idx]
  if ys[yv] == 0 then ys[yv] = nil end
  if not xs[xv] then
    xs[xv] = p[idx]
  else
    xs[xv] = xs[xv] + p[idx]
  end
end
local function work_func()
  local cand = 0
  local xpos, xval, xidx_pos, xidx_val = {}, {}, {}, {}
  for k, v in pairs(xs) do
    table.insert(xpos, k)
    table.insert(xval, v)
  end
  for i = 1, #xpos do xidx_pos[i], xidx_val[i] = i, i end
  table.sort(xidx_pos, function(a, b) return xpos[a] < xpos[b] end)
  table.sort(xidx_val, function(a, b) return xval[a] > xval[b] end)

  local ypos, yval, yidx_pos, yidx_val = {}, {}, {}, {}
  for k, v in pairs(ys) do
    table.insert(ypos, k)
    table.insert(yval, v)
  end
  for i = 1, #ypos do yidx_pos[i], yidx_val[i] = i, i end
  table.sort(yidx_pos, function(a, b) return ypos[a] < ypos[b] end)
  table.sort(yidx_val, function(a, b) return yval[a] > yval[b] end)

  local xcosts = getmincosts(n - 1, xpos, xval, xidx_pos, xidx_val)
  local ycosts = getmincosts(n - 1, ypos, yval, yidx_pos, yidx_val)
  for ik = 0, n - 1 do
    cand = xcosts[0 + 1] + ycosts[ik + 1]
    for i = 1, ik do
      cand = mmi(cand, xcosts[i + 1] + ycosts[ik - i + 1])
    end
    if not retik[ik + 1] then
      retik[ik + 1] = cand
    elseif cand < retik[ik + 1] then
      retik[ik + 1] = cand
    end
  end
end

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

for j = 1, n do
  local xj = x[j]
  if not xs[xj] then
    xs[xj] = p[j]
  else
    xs[xj] = xs[xj] + p[j]
  end
end
for ik = 0, n do
  retik[ik + 1] = false
end

grayWalk(n, add_func, rm_func, work_func)
retik[n + 1] = 0
print(table.concat(retik, "\n"))
-- print(os.clock())

Score: 500 points

Problem Statement

New AtCoder City has an infinite grid of streets, as follows:

At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.

A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.

A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.

There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.

M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.

M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.

For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?

Constraints

1 \leq N \leq 15

-10 \ 000 \leq X_i \leq 10 \ 000

-10 \ 000 \leq Y_i \leq 10 \ 000

1 \leq P_i \leq 1 \ 000 \ 000

The locations of the N residential areas, (X_i, Y_i), are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N

Output

Print the answer in N+1 lines.

The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.

Sample Input 1

3
1 2 300
3 3 600
1 4 800

Sample Output 1

2900
900
0
0

When K = 0, the residents of Area 1, 2, and 3 have to walk the distances of 1, 3, and 1, respectively, to reach a railroad.

Thus, the sum of the walking distances of all citizens, S, is 1 \times 300 + 3 \times 600 + 1 \times 800 = 2900.

When K = 1, if we build a railroad along the street corresponding to the line y = 4 in the coordinate plane, the walking distances of the citizens of Area 1, 2, and 3 become 1, 1, and 0, respectively.

Then, S = 1 \times 300 + 1 \times 600 + 0 \times 800 = 900.

We have many other options for where we build the railroad, but none of them makes S less than 900.

When K = 2, if we build a railroad along the street corresponding to the lines x = 1 and x = 3 in the coordinate plane, all citizens can reach a railroad with the walking distance of 0, so S = 0. We can also have S = 0 when K = 3.

The figure below shows the optimal way to build railroads for the cases K = 0, 1, 2.

The street painted blue represents the roads along which we build railroads.

Sample Input 2

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Sample Output 2

13800
1600
0
0
0
0

The figure below shows the optimal way to build railroads for the cases K = 1, 2.

Sample Input 3

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Sample Output 3

26700
13900
3200
1200
0
0
0

The figure below shows the optimal way to build railroads for the case K = 3.

Sample Input 4

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Sample Output 4

2576709
1569381
868031
605676
366338
141903
0
0
0

The figure below shows the optimal way to build railroads for the case K = 4.


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

local n = io.read("*n")
local x, y, p = {}, {}, {}
local flag = {}
for i = 1, n do
  x[i], y[i], p[i] = io.read("*n", "*n", "*n")
  flag[i] = false
end

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

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
  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 function findright(idxes, ofst)
  for i = ofst, #idxes do
    if flag[idxes[i]] then
      return i
    end
  end
  return false
end

local function getmincost(t, linecnt)
  local pos, val, idx = {}, {}, {}
  for k, v in pairs(t) do
    table.insert(pos, k)
    table.insert(val, v)
  end
  if #pos <= linecnt then
    return 0
  end
  for i = 1, #pos do idx[i] = i end
  table.sort(idx, function(a, b) return val[a] > val[b] end)
  for i = 1, linecnt do
    flag[idx[i]] = true
  end
  for i = linecnt + 1, #pos do
    flag[idx[i]] = false
  end
  local retval = 0
  table.sort(idx, function(a, b) return pos[a] < pos[b] end)
  local leftpos = false
  local rightpos = findright(idx, 1)
  for i = 1, #idx do
    local idx_i = idx[i]
    if flag[idx_i] then
      leftpos = rightpos
      if rightpos then
        rightpos = findright(idx, rightpos + 1)
      end
    else
      local cand = mab(pos[idx_i])
      if leftpos then
        cand = mmi(cand, mab(pos[idx_i] - pos[idx[leftpos]]))
      end
      if rightpos then
        cand = mmi(cand, mab(pos[idx_i] - pos[idx[rightpos]]))
      end
      retval = retval + cand * val[idx_i]
    end
  end
  return retval
end

local ret = false
local g_ik = 0
local xs, ys = {}, {}
local function add_func(idx)
  local xv = x[idx]
  local yv = y[idx]
  xs[xv] = xs[xv] - p[idx]
  if xs[xv] == 0 then xs[xv] = nil end
  if not ys[yv] then
    ys[yv] = p[idx]
  else
    ys[yv] = ys[yv] + p[idx]
  end
end
local function rm_func(idx)
  local xv = x[idx]
  local yv = y[idx]
  ys[yv] = ys[yv] - p[idx]
  if ys[yv] == 0 then ys[yv] = nil end
  if not xs[xv] then
    xs[xv] = p[idx]
  else
    xs[xv] = xs[xv] + p[idx]
  end
end
local function work_func()
  local cand = 0
  for xline = 0, g_ik do
    local yline = g_ik - xline
    local xcost = getmincost(xs, xline)
    local ycost = getmincost(ys, yline)
    local z = xcost + ycost
    if xline == 0 then
      cand = z
    elseif z < cand then
      cand = z
    end
  end
  if not ret then
    ret = cand
  elseif cand < ret then
    ret = cand
  end
end

for ik = 0, n do
  g_ik = ik
  ret = false
  xs, ys = {}, {}
  for j = 1, n do
    local xj = x[j]
    if not xs[xj] then
      xs[xj] = p[j]
    else
      xs[xj] = xs[xj] + p[j]
    end
  end
  grayWalk(n, add_func, rm_func, work_func)
  print(ret)
end