local mod = 1000000007
local mfl = math.floor

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

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

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

local function modinv(src)
  return modpow(src, mod - 2)
end

local function getComb(n, k)
  local ret = 1
  for i = 1, k do
    ret = bmul(ret, n + 1 - i)
    ret = bmul(ret, modinv(i))
  end
  return ret
end

local n, m, k = io.read("*n", "*n", "*n")
local c = getComb(n * m - 2, k - 2)
local a = bmul(n, bmul(n, bmul(m - 1, bmul(m, bmul(m + 1, modinv(6))))))
local b = bmul(m, bmul(m, bmul(n - 1, bmul(n, bmul(n + 1, modinv(6))))))
print(bmul(c, badd(a, b)))

Score : 500 points

Problem Statement

We have a grid of squares with N rows and M columns. Let (i, j) denote the square at the i-th row from the top and j-th column from the left. We will choose K of the squares and put a piece on each of them.

If we place the K pieces on squares (x_1, y_1), (x_2, y_2), ..., and (x_K, y_K), the cost of this arrangement is computed as:

\sum_{i=1}^{K-1} \sum_{j=i+1}^K (|x_i - x_j| + |y_i - y_j|)

Find the sum of the costs of all possible arrangements of the pieces. Since this value can be tremendous, print it modulo 10^9+7.

We consider two arrangements of the pieces different if and only if there is a square that contains a piece in one of the arrangements but not in the other.

Constraints

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

2 \leq K \leq N \times M

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K

Output

Print the sum of the costs of all possible arrangements of the pieces, modulo 10^9+7.

Sample Input 1

2 2 2

Sample Output 1

8

There are six possible arrangements of the pieces, as follows:

((1,1),(1,2)), with the cost |1-1|+|1-2| = 1

((1,1),(2,1)), with the cost |1-2|+|1-1| = 1

((1,1),(2,2)), with the cost |1-2|+|1-2| = 2

((1,2),(2,1)), with the cost |1-2|+|2-1| = 2

((1,2),(2,2)), with the cost |1-2|+|2-2| = 1

((2,1),(2,2)), with the cost |2-2|+|1-2| = 1

The sum of these costs is 8.

Sample Input 2

4 5 4

Sample Output 2

87210

Sample Input 3

100 100 5000

Sample Output 3

817260251

Be sure to print the sum modulo 10^9+7.


local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = self.func(self.stage[i + 1][j * 2 - 1], self.stage[i + 1][j * 2])
    end
  end
end
SegTree.create = function(self, n, func)
  self.func = func
  local stagenum, mul = 1, 1
  self.cnt, self.stage, self.size = {1}, {{}}, {}
  while mul < n do
    mul, stagenum = mul * 2, stagenum + 1
    self.cnt[stagenum], self.stage[stagenum] = mul, {}
  end
  for i = 1, stagenum do self.size[i] = self.cnt[stagenum + 1 - i] end
  self.stagenum = stagenum
  for i = 1, mul do self.stage[stagenum][i] = {0, 0LL} end
  self:updateAll()
end
SegTree.setValue = function(self, idx, value)
  self.stage[self.stagenum][idx] = value
  for i = self.stagenum - 1, 1, -1 do
    local dst = mce(idx / 2)
    local rem = dst * 4 - 1 - idx
    self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
    idx = dst
  end
end
SegTree.new = function(n, func)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func)
  return obj
end

SegTree.lower_bound = function(self, val)
  local ret, retpos = {0, 0LL}, 0
  local t1, t2, t3 = {1}, {1}, {self.size[1]}
  local retval = 0
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    if sz <= r + 1 - l then
      local tmp = self.func(ret, self.stage[stage][mce(l / sz)])
      if tmp[1] < val then
        ret, retpos = tmp, l + sz - 1
        retval = tmp[2]
        if sz ~= 1 then table.insert(t1, stage + 1) table.insert(t2, l + sz) table.insert(t3, r) end
      else
        if sz ~= 1 then table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, l + sz - 2) end
      end
    else
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, r)
    end
  end
  return retpos + 1, retval
end

local q = io.read("*n")
local qlist = {}
local alist = {}
for i = 1, q do
  local tp = io.read("*n")
  if tp == 1 then
    local a, b = io.read("*n", "*n")
    qlist[i] = {a, b}
    table.insert(alist, a)
  else
    qlist[i] = false
  end
end
table.sort(alist)
local amap = {}
local asum = {}
local addcnt = {}
for i = 1, #alist do
  if not amap[alist[i]] then
    amap[alist[i]] = i
  end
  if i == 1 then asum[i] = alist[i]
  else asum[i] = asum[i - 1] + alist[i]
  end
  addcnt[alist[i]] = 0
end
local tree = SegTree.new(#alist, function(x, y) return {x[1] + y[1], x[2] + y[2]} end)
local acnt = 0
local bsum = 0
for i = 1, q do
  local query = qlist[i]
  if query then
    local a = query[1]
    local tmp = addcnt[a]
    local addpos = amap[query[1]] + tmp
    addcnt[a] = tmp + 1
    tree:setValue(addpos, {1, 0LL + a})
    bsum = bsum + query[2]
    acnt = acnt + 1
  else
    local half = mfl((acnt + 1) / 2)
    local calcpos, preval = tree:lower_bound(half)
    local src = alist[calcpos]
    preval = preval + src
    local curtot = tree.stage[1][1][2]
    local result = bsum + half * src - preval
      + (curtot - preval) - (acnt - half) * src
    print(src .. " " .. tostring(result):gsub("LL", ""))
  end
end

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

Score : 600 points

Problem Statement

There is a function f(x), which is initially a constant function f(x) = 0.

We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:

An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).

An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.

We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

Constraints

All values in input are integers.

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

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

The first query is an update query.

Input

Input is given from Standard Input in the following format:

Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

Output

For each evaluation query, print a line containing the response, in the order in which the queries are given.

The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

Sample Input 1

4
1 4 2
2
1 1 -8
2

Sample Output 1

4 2
1 -3

In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.

In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.

Sample Input 2

4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2

Sample Output 2

-1000000000 3000000000

Submitted source-code file size, in bytes.

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

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


local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = self.func(self.stage[i + 1][j * 2 - 1], self.stage[i + 1][j * 2])
    end
  end
end
SegTree.create = function(self, ary, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.cnt, self.stage, self.size = {1}, {{}}, {}
  while mul < #ary do
    mul, stagenum = mul * 2, stagenum + 1
    self.cnt[stagenum], self.stage[stagenum] = mul, {}
  end
  for i = 1, stagenum do self.size[i] = self.cnt[stagenum + 1 - i] end
  self.stagenum = stagenum
  for i = 1, #ary do self.stage[stagenum][i] = ary[i] end
  for i = #ary + 1, mul do self.stage[stagenum][i] = emptyvalue end
  self:updateAll()
end
SegTree.getRange = function(self, left, right)
  if left == right then return self.stage[self.stagenum][left] end
  local start_stage = 1
  while right - left + 1 < self.size[start_stage] do
    start_stage = start_stage + 1
  end
  local ret = self.emptyvalue
  local t1, t2, t3 = {start_stage}, {left}, {right}
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    if (l - 1) % sz ~= 0 then
      local newr = mmi(r, mce((l - 1) / sz) * sz)
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, newr)
      l = newr + 1
    end
    if sz <= r + 1 - l then
      ret = self.func(ret, self.stage[stage][mce(l / sz)])
      l = l + sz
    end
    if l <= r then
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, r)
    end
  end
  return ret
end
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = value
  if not silent then
    for i = self.stagenum - 1, 1, -1 do
      local dst = mce(idx / 2)
      local rem = dst * 4 - 1 - idx
      self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
      idx = dst
    end
  end
end
SegTree.new = function(ary, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(ary, func, emptyvalue)
  return obj
end

SegTree.lower_bound = function(self, val)
  local ret, retpos = self.emptyvalue, 0
  local t1, t2, t3 = {1}, {1}, {self.size[1]}
  local retval = 0
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    if sz <= r + 1 - l then
      local tmp = self.func(ret, self.stage[stage][mce(l / sz)])
      if tmp[1] < val then
        ret, retpos = tmp, l + sz - 1
        retval = tmp[2]
        if sz ~= 1 then table.insert(t1, stage + 1) table.insert(t2, l + sz) table.insert(t3, r) end
      else
        if sz ~= 1 then table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, l + sz - 2) end
      end
    else
      table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, r)
    end
  end
  return retpos + 1, retval
end

local q = io.read("*n")
local qlist = {}
local alist = {}
for i = 1, q do
  local tp = io.read("*n")
  if tp == 1 then
    local a, b = io.read("*n", "*n")
    qlist[i] = {a, b}
    table.insert(alist, a)
  else
    qlist[i] = false
  end
end
table.sort(alist)
local amap = {}
local asum = {}
local addcnt = {}
for i = 1, #alist do
  if not amap[alist[i]] then
    amap[alist[i]] = i
  end
  if i == 1 then asum[i] = alist[i]
  else asum[i] = asum[i - 1] + alist[i]
  end
  addcnt[alist[i]] = 0
end
local stary = {}
for i = 1, #alist do stary[i] = {0, 0LL} end
local tree = SegTree.new(stary, function(x, y) return {x[1] + y[1], x[2] + y[2]} end, {0, 0LL})
local acnt = 0
local bsum = 0
for i = 1, q do
  local query = qlist[i]
  if query then
    local a = query[1]
    local tmp = addcnt[a]
    local addpos = amap[query[1]] + tmp
    addcnt[a] = tmp + 1
    tree:setValue(addpos, {1, 0LL + a})
    bsum = bsum + query[2]
    acnt = acnt + 1
  else
    local half = mfl((acnt + 1) / 2)
    local calcpos, preval = tree:lower_bound(half)
    local src = alist[calcpos]
    preval = preval + src
    local curtot = tree.stage[1][1][2]
    local result = bsum + half * src - preval
      + (curtot - preval) - (acnt - half) * src
    print(src .. " " .. tostring(result):gsub("LL", ""))
  end
end


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local n, k = io.read("*n", "*n", "*l")
local s = io.read()
for i = 1, n do
  if(i ~= k) then io.write(s:sub(i, i))
  else
    io.write(string.char(s:byte(i, i) + 32))
  end
end
io.write("\n")

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local s = io.read()
local a, b = s:match("(%d%d)(%d%d)")
a, b = tonumber(a), tonumber(b)
local my, ym = false, false
if(1 <= a and a <= 12) then
  my = true
end
if(1 <= b and b <= 12) then
  ym = true
end
if my and ym then print("AMBIGUOUS")
elseif my then print("MMYY")
elseif ym then print("YYMM")
else print("NA")
end

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


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 n=io.read("n")
local graph={}
for i=1,n do
    graph[i]={}
end
for i=1,n-1 do
    local u,v,w=io.read("n","n","n")
    graph[u][v]=w
    graph[v][u]=w
end

local stack=List.new()
List.pushright(stack,{1,0})
local checked={}
local color={0}

while not List.empty(stack) do
    local pop=List.popright(stack)
    local u=pop[1]
    local w=pop[2]
    checked[u]=true
    for v,_ in pairs(graph[u]) do
        if not checked[v] then
            local nw=w+graph[u][v]
            color[i]=nw%2
            List.pushright(stack,{v,nw})
        end
    end
end

for i=1,n do
    print(color[i])
end

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

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

Sample Output 2

1
0
1
0
1


local n = io.read("*n")
local edge = {}
local len = {}
for i = 1, n do
  edge[i] = {}
  len[i] = -1
end
for i = 1, n - 1 do
  local u, v, w = io.read("*n", "*n", "*n")
  edge[u][v], edge[v][u] = w, w
end
len[1] = 0
local tasks = {1}
for i = 1, n do
  local src = tasks[i]
  if not src then break end
  for dst, cost in pairs(edge[src]) do
    if len[dst] < 0 then
      len[dst] = len[src] + cost
      table.insert(tasks, dst)
    end
  end
end
for i = 1, n do
  print(len[i] % 2)
end


--
local N, M = io.read("n", "n")

-- from ABC120
local parents = {}
for i=1,N do
    parents[i] = -1
end
local function find_root(x)
    while parents[x] > 0 do
        x = parents[x]
    end
    return x
end
local function find_union(a, b, update)
    local x, y = a, b
    while parents[x] > 0 do
        x = parents[x]
    end
    while parents[y] > 0 do
        y = parents[y]
    end
    local size_a, size_b = -parents[x], -parents[y]
    if update and x ~= y then
        if size_b > size_a then
            x, y = y, x
        end
        -- size(x) > size(y)
        -- x is new root of y
        parents[x] = parents[x] + parents[y]
        parents[y] = x
    end
    return x == y, size_a, size_b
end

for i=1,M do
    local a,b,z = io.read("n", "n", "n")
    find_union(a,b,true)
end

local set = {}
for i=1,N do
    local r = find_root(i)
    set[r] = true
end
local count = 0
for _ in pairs(set) do
    count = count + 1
end
print(count)

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


r,g,b,n=io.read("*n","*n","*n","*n")

counter=0
for i=0,n do
    for j=0,n-i do
        rg=r*i+g*j
        if n>=rg and (n-rg)%b==0 then
            counter=counter+1
        end
    end
end
print(counter)

Score : 200 points

Problem Statement

Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:

Red boxes, each containing R red balls

Green boxes, each containing G green balls

Blue boxes, each containing B blue balls

Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes.
How many triples of non-negative integers (r,g,b) achieve this?

Constraints

All values in input are integers.

1 \leq R,G,B,N \leq 3000

Input

Input is given from Standard Input in the following format:

R G B N

Output

Print the answer.

Sample Input 1

1 2 3 4

Sample Output 1

4

Four triples achieve the objective, as follows:

(4,0,0)

(2,1,0)

(1,0,1)

(0,2,0)

Sample Input 2

13 1 4 3000

Sample Output 2

87058


r,g,b,n=io.read("*n","*n","*n","*n")

counter=0
for i=0,3000 do
    for j=0,3000 do
        rg=r*i+g*j
        if n>=rg and (n-rg)%b==0 then
            counter=counter+1
        end
    end
end
print(counter)


r,g,b,n=io.read("*n","*n","*n","*n")

counter=0
for i=0,n do
    for j=0,n do
        rg=r*i+g*j
        if n>=rg and (n-rg)%b==0 then
            counter=counter+1
        end
    end
end
print(counter)


local n = io.read("*n", "*l")
local cnt = 0
local w_a , w_b, w_ab = 0, 0, 0
for i = 1, n do
  local ss = io.read()
  for p in ss:gmatch("AB") do
    cnt = cnt + 1
  end
  ss = ss:gsub("AB", "")
  local a, b = false, false
  if 0 < #ss then
    if ss:sub(1, 1) == "B" then
      b = true
    end
    if ss:sub(#ss, #ss) == "A" then
      a = true
    end
    if a and b then w_ab = w_ab + 1
    elseif a then w_a = w_a + 1
    elseif b then w_b = w_b + 1
    end
  end
end
if 0 < w_a or 0 < w_b then
  print(cnt + w_ab + math.min(w_a, w_b))
else
  print(cnt + math.max(0, w_ab - 1))
end

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


local ior = io.input()
local n = ior:read("*n", "*l")
local num_b_st_a_ed = 0
local num_b_st = 0
local num_a_ed = 0

local tot = 0

for i = 1, n do
  local str = ior:read()
  local len = #str
  local isfirst = true
  local bcand = false
  local adet = false
  if(str:sub(1, 1) == "B") then bcand = true end
  if(str:sub(len, len) == "A") then adet = true end
  for j = 1, len - 1 do
    if(str:sub(j, j) == "A" and str:sub(j + 1, j + 1) == "B") then
      tot = tot + 1
      -- print("FOUND")
    end
  end
  if(adet and bcand) then
    num_b_st_a_ed = num_b_st_a_ed + 1
    -- print(i, "BA")
  elseif(adet) then
    num_a_ed = num_a_ed + 1
    -- print(i, "-A")
  elseif(bcand) then
    num_b_st = num_b_st + 1
    -- print(i, "B-")
  end
end
-- print(num_a_ed, num_b_st, num_b_st_a_ed)
if(num_a_ed == 0 and num_b_st == 0) then
  if(0 < num_b_st_a_ed) then
    tot = tot + num_b_st_a_ed - 1
  end
else
  tot = tot + num_b_st_a_ed + math.min(num_a_ed, num_b_st)
end
print(tot)


local N = io.read("n", "l")
local inner = 0
local endsA = 0 -- but not starts w/ B
local startsB = 0 -- but not ends w/ A
local both = 0
for i=1, N do
    local s = io.read("l")
    local head = string.sub(s, 1, 1)
    local tail = string.sub(s, #s, #s)
    if head == 'B' and tail == 'A' then
        both = both + 1
    elseif head == 'B' then
        startsB = startsB + 1
    elseif tail == 'A' then
        endsA = endsA + 1
    end
    for _ in string.gmatch(s, "AB") do
        inner = inner + 1
    end
end
local ans = inner
if both > 0 then
    ans = ans + both - 1
    if endsA > 0 then
        ans = ans + 1
        endsA = endsA - 1
    end
    if startsB > 0 then
        ans = ans + 1
        startsB = startsB - 1
    end
end
ans = ans + math.min(endsA, startsB)
print(ans)


local mce, mfl, msq, mmi, mma, mab = math.ceil, math.floor, math.sqrt, math.min, math.max, math.abs

local function getprimes(x)
  local primes = {}
  local allnums = {}
  for i = 1, x do allnums[i] = true end
  for i = 2, x do
    if allnums[i] then
      table.insert(primes, i)
      local lim = mfl(x / i)
      for j = 2, lim do
        allnums[j * i] = false
      end
    end
  end
  return primes
end

local function getdivisorparts(x, primes)
  local prime_num = #primes
  local tmp = {}
  local lim = mce(msq(x))
  local primepos = 1
  local dv = primes[primepos]
  while primepos <= prime_num and dv <= lim do
    if x % dv == 0 then
      local t = {}
      t.p = dv
      t.cnt = 1
      x = mfl(x / dv)
      while x % dv == 0 do
        x = mfl(x / dv)
        t.cnt = t.cnt + 1
      end
      table.insert(tmp, t)
      lim = mce(msq(x))
    end
    if primepos == prime_num then break end
    primepos = primepos + 1
    dv = primes[primepos]
  end
  if x ~= 1 then
    local t = {}
    t.p, t.cnt = x, 1
    table.insert(tmp, t)
  end
  return tmp
end

local function getdivisorCore(divisorparts)
  local t = {}
  local pat = 1
  local len = #divisorparts
  local allpat = 1
  for i = 1, len do
    allpat = allpat * (1 + divisorparts[i].cnt)
  end
  for t_i_pat = 0, allpat - 1 do
    local div = allpat
    local i_pat = t_i_pat
    local ret = 1
    for i = 1, len do
      div = mfl(div / (divisorparts[i].cnt + 1))
      local mul = mfl(i_pat / div)
      i_pat = i_pat % div
      for j = 1, mul do
        ret = ret * divisorparts[i].p
      end
    end
    table.insert(t, ret)
  end
  -- table.sort(t)
  return t
end

local function getdivisor(x, primes)
  local dvp = getdivisorparts(x, primes)
  return getdivisorCore(dvp)
end

local n = io.read("*n")
local primes = getprimes(mce(msq(n)))
local divs = getdivisor(n, primes)
local ret = 0
for i = 1, #divs do
  local mp1 = divs[i]
  local k = n // mp1
  if k < mp1 - 1 then
    ret = ret + mp1 - 1
  end
end
print(ret)

Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


local a, b, t = io.read("n","n","n")
local ans = (t//a) * b
print(ans)


n = io.read"*n"
v = {io.read((("*n"):rep(n)):match(("(*n)"):rep(n)))}
c = {io.read((("*n"):rep(n)):match(("(*n)"):rep(n)))}
r = 0
for i=1,n do
	x = v[i]-c[i]
	r = x<0 and r or x+r
end
print(r)

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

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


local ior = io.read
local n = ior("*n")
local t = {}
local minus = 0
for i = 1, n do
  local a = ior("*n")
  if(a < 0) then minus = minus + 1 end
  t[i] = a
end
table.sort(t)
local ma = math.abs
if(minus % 2 == 0) then
  local sum = 0
  for i = 1, n do
    sum = sum + ma(t[i])
  end
  print(sum)
else
  local sum = 0
  for i = 1, minus - 1 do
    sum = sum + ma(t[i])
  end
  if(minus < n) then
    sum = sum + ma(t[minus + 1] + t[minus])
  end
  for i = minus + 2, n do
    sum = sum + t[i]
  end
  print(sum)
end


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

local function str2numtbl(s, offset)
    local t = {string.byte(s, 1, #s)}
    if offset then
        for i=1, #t do
            t[i] = t[i] - offset
        end
    end
    return t
end

--local function each_char2(s)
--    return ipairs(str2tbl(s))
--end

local function each_char(s)
    local f = function(_, i)
        i = i + 1
        if i <= #s then
            return i, string.sub(s, i, i)
        end
    end
    return f, nil, 0
end

function string.at(s, i)
    return string.sub(s, i, i)
end

--
local N,_,S,K = io.read("n", "l", "l", "n")
local c = S:at(K)
local ans = string.gsub(S, "[^"..c.."]", "*")
print(ans)

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

S is a string of length N consisting of lowercase English letters.

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


local a,b=io.read("*n","*n")
local ans=0
if a>b then
  ans=ans+a
  a=a-1
else
  ans=ans+b
  b=b-1
end
print(ans+math.max(a,b))

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


a,b=io.read():match("(.+)%s(.+)")
a=a*1
b=b*1
print(a>=b+1 and math.floor(2*a-1) or b>=a+1 and math.floor(2*b-1)or math.floor(2*a))


-- A
local A, B = io.read("n", "n")
local ans = {A+A-1, A+B, B+B-1}
table.sort(ans)
print(ans[3])


n = io.read("*n")
maior = 0
tot = 0
for i=0, n - 1 do
    number = io.read("*n")
    if (number >= maior) then
        maior = number
        tot = tot + 1
    end
end
print(tot)

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


n = io.read("*n")
h = 0
c = 0
for i = 1, n do
  a = io.read("*n")
  if h <= a then
    c, h = c + 1, a
  end
end
print(c)


-- B
local N = io.read("n")
local H = {}
for i=1,N do H[i] = io.read("n") end
local ans = 1
local max = H[1]
for i=2,N do
    if H[i] >= max then
        ans = ans + 1
        max = H[i]
    end
end
print(ans)


S = io.read()
a, b, c, d = 0, 0, 0, 0

for i=1, #S do
    if i%2==0 then
        a = a + 1
        if S:sub(i,i)=="0" then
        b = b + 1
        end
    elseif i%2==1 then
        c = c + 1
        if S:sub(i,i)=="1" then
            d = d + 1
        end
    end
end
print(math.min(b+d, a+c-(b+d)))

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


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

local function each_char2(s)
    return ipairs(str2tbl(s))
end

local function each_char(s)
    local f = function(_, i)
        i = i + 1
        if i <= #s then
            return i, string.sub(s, i, i)
        end
    end
    return f, nil, 0
end

function string.at(s, i)
    return string.sub(s, i, i)
end

-- C
local S = {}
while true do
    local c = io.read(1)
    if c == "1" then
        table.insert(S, 1)
    elseif c == "0" then
        table.insert(S, 0)
    else
        break
    end
end
local oddeven_01, oddeven_10 = 0, 0
for i=1,#S do
    local x = S[i]
    if i & 1 == 1 then
        -- odd
        if x == 1 then
            oddeven_01 = oddeven_01 + 1
        elseif x == 0 then
            oddeven_10 = oddeven_10 + 1
        end
    else
        -- even
        if x == 1 then
            oddeven_10 = oddeven_10 + 1
        elseif x == 0 then
            oddeven_01 = oddeven_01 + 1
        end
    end
end
local min = oddeven_01
if min > oddeven_10 then
    min = oddeven_10
end
print(min)


-- D
local N, Kmax, _, tmp = io.read("n", "n", "l", "l")
local S = {}
local ZZ = string.byte('0')
for i=1, N do
    S[i] = string.byte(tmp, i, i) - ZZ
end
local rlast = 1
local k = 0
local left = 1
local ans = 0
for right=1, N do
    if rlast == 1 and S[right] == 0 then
        k = k + 1
    end
    rlast = S[right]
    while k > Kmax do
        local llast = S[left]
        left = left + 1
        if llast == 0 and S[left] == 1 then
            k = k - 1
        end
    end
    assert(right >= left)
    local v = right - left + 1
    if ans < v then
        ans = v
    end
end
print(ans)

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


a,b,c,d,e,k=io.read("n","n","n","n","n","n","n")
t={a,b,c,d,e}
for i=1,#t-1 do
	for j=i+1,#t do
		if t[j]-t[i]>k then
			print(":(")
			return
		end
	end
end
print("Yay!")

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


t = {}
for i = 1, 5 do
  t[i] = io.read("*n")
end
table.sort(t, function(a, b)
  if a % 10 == b % 10 then return false
  else
    va = a % 10
    vb = b % 10
    if va == 0 then va = 10 end
    if vb == 0 then vb = 10 end
    return va < vb
  end
end
)
ret = t[1]
for i = 2, 5 do
  ret = ret + 10 * math.ceil(t[i] / 10)
end
print(ret)

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


-- C
local N = io.read("n")
local INF=N+1
local capa = {}
for i=1,5 do
    capa[i] = io.read("n")
end
-- which edge is bottleneck?
local bn_i = 0
local bn_capa = INF
for i=1,#capa do
    if capa[i] < bn_capa then
        bn_capa = capa[i]
        bn_i = i
    end
end
if bn_capa == INF then
    print(5)
    return
end
local ans
ans = N // bn_capa
if N % bn_capa ~= 0 then
    ans = ans + 1
end
ans = ans + bn_i - 1
ans = ans + 5 - bn_i
print(ans)

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

Note that the input or output may not fit into a 32-bit integer type.


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

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

local function dbgpr_tp(tbl)
    dbgpr_t(tbl, true)
end

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

local function each_char(s)
    local f = function(_, i)
        i = i + 1
        if i <= #s then
            return i, string.sub(s, i, i)
        end
    end
    return f, nil, 0
end
local N, Q, _ = io.read("n", "n", "l")
local s = io.read("l")
assert(#s == N)
local spells = {}
for i=1,Q do
    local t, _, d, _ = io.read(1, 1, 1, "l")
    spells[i] = {t, d}
end

local place = str2tbl(s)

local left, right
local left_path, right_path = 0, N+1
local left_mostr, right_mostl = 0, N+1

for i=Q,1,-1 do
    local t, d = spells[i][1], spells[i][2]
    local flag = true
    if d == 'L' then
        if t == place[1] and not left then
            left_path = 1
            flag = false
            left = true
        end
    else
        if t == place[N] and not right then
            right_path = N
            flag = false
            right = true
        end
    end
    if flag then
        if left then
            if d == 'L' and t == place[left_path+1] then
                left_path = left_path+1
            elseif d == 'R' and t == place[left_path-1] then
                left_path = left_path-1
            end
        end
        if right then
            if d == 'L' and t == place[right_path+1] then
                right_path = right_path+1
            elseif d == 'R' and t == place[right_path-1] then
                right_path = right_path-1
            end
        end
    end
    if left_path > left_mostr then
        left_mostr = left_path
    end
    if right_path < right_mostl then
        right_mostl = right_path
    end
end

local dead = 0
for i=1,N do
    if i <= left_mostr or i >= right_mostl then
        dead = dead + 1
    end
end
print(N - dead)

Score : 500 points

Problem Statement

There are N squares numbered 1 to N from left to right.
Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.

Snuke cast Q spells to move the golems.

The i-th spell consisted of two characters t_i and d_i, where d_i is L or R.
When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is L, and moved to the square adjacent to the right if d_i is R.

However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.

Find the number of golems remaining after Snuke cast the Q spells.

Constraints

1 \leq N,Q \leq 2 \times 10^{5}

|s| = N

s_i and t_i are uppercase English letters.

d_i is L or R.

Input

Input is given from Standard Input in the following format:

N Q
s
t_1 d_1
\vdots
t_{Q} d_Q

Output

Print the answer.

Sample Input 1

3 4
ABC
A L
B L
B R
A R

Sample Output 1

2

Initially, there is one golem on each square.

In the first spell, the golem on Square 1 tries to move left and disappears.

In the second spell, the golem on Square 2 moves left.

In the third spell, no golem moves.

In the fourth spell, the golem on Square 1 moves right.

After the four spells are cast, there is one golem on Square 2 and one golem on Square 3, for a total of two golems remaining.

Sample Input 2

8 3
AABCBDBA
A L
B R
A R

Sample Output 2

5

After the three spells are cast, there is one golem on Square 2, two golems on Square 4 and two golems on Square 6, for a total of five golems remaining.

Note that a single spell may move multiple golems.

Sample Input 3

10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L

Sample Output 3

3


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

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

local function dbgpr_tp(tbl)
    dbgpr_t(tbl, true)
end

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

local function each_char(s)
    local f = function(_, i)
        i = i + 1
        if i <= #s then
            return i, string.sub(s, i, i)
        end
    end
    return f, nil, 0
end
local N, Q, _ = io.read("n", "n", "l")
local s = io.read("l")
assert(#s == N)
local spells = {}
for i=1,Q do
    local t, _, d, _ = io.read(1, 1, 1, "l")
    spells[i] = {t, d}
end

local place = str2tbl(s)

local paths = {}

local function new_path(pos)
    local p = {pos, 1}
    return p
end
local function push_path(p)
    table.insert(paths, p)
end

for i=Q,1,-1 do
    local t, d = spells[i][1], spells[i][2]
    local flag = true
    if d == 'L' then
        if t == place[1] then
            local p = new_path(1)
            push_path(p)
            flag = false
        end
    else
        if t == place[N] then
            local p = new_path(N)
            push_path(p)
            flag = false
        end
    end
    if flag then
        for _,p in ipairs(paths) do
            local pos, count = p[1], p[2]
            if d == 'L' then
                if t == place[pos+1] then
                    p[1], p[2] = pos+1, count+1
                end
            else
                if t == place[pos-1] then
                    p[1], p[2] = pos-1, count+1
                end
            end
        end
    end
end
local dead = 0
for _,p in ipairs(paths) do
    dead = dead + p[2]
end
print(N - dead)


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

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

local function dbgpr_tp(tbl)
    dbgpr_t(tbl, true)
end

local function each_char(s)
    local f = function(_, i)
        i = i + 1
        if i <= #s then
            return i, string.sub(s, i, i)
        end
    end
    return f, nil, 0
end
local N, Q, _ = io.read("n", "n", "l")
local s = io.read("l")
dbgpr(N, Q, s)
assert(#s == N)
local spells = {}
for i=1,Q do
    local t, _, d, _ = io.read(1, 1, 1, "l")
    spells[i] = {t, d}
end

local places = {}
local AA, ZZ = string.byte("AZ", 1, 2)
for i=AA,ZZ do
    local c = string.char(i)
    places[c] = {}
end

local count = {}
for i=1,N do
    local c = string.sub(s, i, i)
    table.insert(places[c], i)
    count[i] = 1
end
for i=AA,ZZ do
    local c = string.char(i)
    dbgpr(c)
    dbgpr_t(places[c])
end

local dead = 0
for i=1,Q do
    local t, d = spells[i][1], spells[i][2]
    local a = (d == 'L') and -1 or 1
    for _,v in ipairs(places[t]) do
        if count[v] > 0 then
            local oldcount = count[v]
            count[v] = 0
            if v + a <= 0 then
                dead = dead + oldcount
            elseif v + a > N then
                dead = dead + oldcount
            else
                count[v+a] = count[v+a] + oldcount
            end
        end
    end
    dbgpr_tp(count)
end
print(N - dead)


n, q = io.read("*n", "*n", "*l")
s = io.read()
t = {}
num = {}
for i = 1, n do
    a = string.sub(s, i, i)
    if(t[a] == nil) then
        t[a] = {i}
    else
        table.insert(t[a], i)
    end
    num[i] = 1
end
for i = 1, q do
    tgt, zz, way = io.read(1, 1, "*l")
    if(way == "L") then
        if(t[tgt] ~= nil) then
            table.sort(t[tgt])
            for k, v in pairs(t[tgt]) do
                if(1 < v) then
                    num[v - 1] = num[v - 1] + num[v]
                end
                num[v] = 0
            end
        end
    else
        if(t[tgt] ~= nil) then
            table.sort(t[tgt], function(aa, ab) return aa > ab end)
            for k, v in pairs(t[tgt]) do
                if(v < n) then
                    num[v + 1] = num[v + 1] + num[v]
                end
                num[v] = 0
            end
        end
    end
end
sum = 0
for i = 1, n do
    sum = sum + num[i]
end
print(sum)


local mod = 1000000007
local mfl = math.floor

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

local n, x = io.read("*n", "*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
table.sort(a)
local t = {}
for i = 1, n do
  t[i] = {}
  for j = 1, n - i + 1 do
    t[i][j] = {}
  end
end
for i = 1, n do
  t[i][n + 1 - i][x % a[i]] = 1
end
for src = n, 1, -1 do
  for rem = n - src + 1, 2, -1 do
    for val, cnt in pairs(t[src][rem]) do
      local add = bmul(cnt, rem - 1)
      if t[src][rem - 1][val] then
        t[src][rem - 1][val] = badd(t[src][rem - 1][val], add)
      else
        t[src][rem - 1][val] = add
      end
    end
  end
  for rem = 1, n - src + 1 do
    for val, cnt in pairs(t[src][rem]) do
      for dst = src - 1, 1, -1 do
        local nval = val % a[dst]
        local step = src - dst - 1
        if t[dst][rem + step][nval] then
          t[dst][rem + step][nval] = badd(t[dst][rem + step][nval], cnt)
        else
          t[dst][rem + step][nval] = cnt
        end
      end
    end
  end
end
local ret = 0
for k, v in pairs(t[1][1]) do
  ret = badd(ret, bmul(k, v))
end
print(ret)

Score : 600 points

Problem Statement

Snuke has a blackboard and a set S consisting of N integers.
The i-th element in S is S_i.

He wrote an integer X on the blackboard, then performed the following operation N times:

Choose one element from S and remove it.

Let x be the number written on the blackboard now, and y be the integer removed from S. Replace the number on the blackboard with x \bmod {y}.

There are N! possible orders in which the elements are removed from S.
For each of them, find the number that would be written on the blackboard after the N operations, and compute the sum of all those N! numbers modulo 10^{9}+7.

Constraints

All values in input are integers.

1 \leq N \leq 200

1 \leq S_i, X \leq 10^{5}

S_i are pairwise distinct.

Input

Input is given from Standard Input in the following format:

N X
S_1 S_2 \ldots S_{N}

Output

Print the answer.

Sample Input 1

2 19
3 7

Sample Output 1

3

There are two possible orders in which we remove the numbers from S.

If we remove 3 and 7 in this order, the number on the blackboard changes as follows: 19 \rightarrow 1 \rightarrow 1.

If we remove 7 and 3 in this order, the number on the blackboard changes as follows: 19 \rightarrow 5 \rightarrow 2.

The output should be the sum of these: 3.

Sample Input 2

5 82
22 11 6 5 13

Sample Output 2

288

Sample Input 3

10 100000
50000 50001 50002 50003 50004 50005 50006 50007 50008 50009

Sample Output 3

279669259

Be sure to compute the sum modulo 10^{9}+7.


Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


local a=io.read()
if a=='A'then
  print('T')
elseif a=='C'then
  print('G')
elseif a=='G'then
  print('C')
else
  print('A')
end


a=io.read()
print(a=="A"and"T"or a=="T"and"A"or a=="G"and"C"or"G")


s = io.read()
z = 0
for a in string.gmatch(s, "([ATCG]+)") do z = math.max(z, string.len(a)) end
print(z)

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

S is a string of length between 1 and 10 (inclusive).

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


ans=0
for i in io.read():gmatch("[ACGT]+")do
  ans=math.max(ans,#i)
end
print(ans)


local N, Q, _ = io.read("n", "n", "l")
local S_tmp = io.read("l")
local S = {}
for i=1,N do
    S[i] = string.sub(S_tmp, i, i)
end

local tbl = {}
tbl[0] = 0
local prev = '_'
for i=1,N do
    local c = S[i]
    if prev .. c == 'AC' then
        tbl[i] = tbl[i-1] + 1
    else
        tbl[i] = tbl[i-1]
    end
    prev = c
end

for i=1,Q do
    local l, r = io.read("n", "n")
    local count = tbl[r] - tbl[l]
    print(count)
end

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


local N, Q, _ = io.read("n", "n", "l")
local S = io.read("l")
for i=1,Q do
    local l, r = io.read("n", "n")
    local ss = string.sub(S, l, r)
    local _, count = string.gsub(ss, 'AC', '!!')
    print(count)
end


local N = io.read("n")

local MOD = 1000000007
local chars = {'A', 'C', 'G', 'T'}
local tbl = {}

function tbl.lookup(n, c1, c2, c3)
    local val = tbl[tostring(n) .. c1 .. c2 .. c3]
    if not val then
        val = 0
        tbl[tostring(n) .. c1 .. c2 .. c3] = val
    end
    return val
end

function tbl.update(n, c1, c2, c3, val)
    tbl[tostring(n) .. c1 .. c2 .. c3] = val
end

tbl.update(0,'T','T','T',1)

for i=1,N do
    for k=0,63 do
        local c1 = chars[(k & 3) + 1]
        local c2 = chars[((k >> 2) & 3) + 1]
        local c3 = chars[((k >> 4) & 3) + 1]
        if tbl.lookup(i-1, c1, c2, c3) ~= 0 then
            for _,a in pairs(chars) do
                local ng_cond = a .. c1 .. c2 == 'AGC'
                            or a .. c1 .. c2 == 'ACG'
                            or a .. c1 .. c2 == 'GAC'
                            or a .. c2 .. c3 == 'AGC'
                            or a .. c1 .. c3 == 'AGC'
                if not ng_cond then
                    local old = tbl.lookup(i, a, c1, c2)
                    local origin = tbl.lookup(i-1, c1, c2, c3)
                    tbl.update(i, a, c1, c2, (old + origin) % MOD)
                end
            end
        end
    end
end

local ans = 0
for k=0,63 do
    local c1 = chars[(k & 3) + 1]
    local c2 = chars[((k >> 2) & 3) + 1]
    local c3 = chars[((k >> 4) & 3) + 1]
    ans = (ans + tbl.lookup(N, c1, c2, c3)) % MOD
end

print(ans)

Score : 400 points

Problem Statement

You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:

The string does not contain characters other than A, C, G and T.

The string does not contain AGC as a substring.

The condition above cannot be violated by swapping two adjacent characters once.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

61

There are 4^3 = 64 strings of length 3 that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is 64 - 3 = 61.

Sample Input 2

4

Sample Output 2

230

Sample Input 3

100

Sample Output 3

388130742

Be sure to print the number of strings modulo 10^9+7.


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

local a={}
for i=1,n do
    for j=#b,1,-1 do
        if b[j]==j then
            table.remove(b,j)
            a[i]=j
            break
        end
    end
end

if #a==n then
    for i=n,1,-1 do
        print(a[i])
    end
else
    print(-1)
end

Score : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1).

You are given a sequence b of length N. Determine if it is possible that a is equal to b after N operations. If it is, show one possible sequence of operations that achieves it.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

If there is no sequence of N operations after which a would be equal to b, print -1.
If there is, print N lines. In the i-th line, the integer chosen in the i-th operation should be printed. If there are multiple solutions, any of them is accepted.

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

In this sequence of operations, the sequence a changes as follows:

After the first operation: (1)

After the second operation: (1,1)

After the third operation: (1,2,1)

Sample Input 2

2
2 2

Sample Output 2

-1

2 cannot be inserted at the beginning of the sequence, so this is impossible.

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1


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

local t={}
for i=1,n do
    local a=s:sub(i,i)
    if not t[a] then
        t[a]=1
    else
        t[a]=t[a]+1
    end
end

local combination=1
for _,frequency in pairs(t) do
    combination=combination*(frequency+1)%1000000007
end
print(combination-1)

Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17


local n, s = io.read("l","l")
local cnt = {}
for i = 1, n do
    local ch = string.sub(s, i, i)
    cnt[ch] = (cnt[ch] or 1) + 1
end
local ans = 1
for _, v in pairs(cnt) do
    ans = ans * v
end
print(ans - 1)


local n = io.read("n")
local colpos, col, dp= {}, {}, {}
local last = -1
mof = 1000000000+7
for i = 1, n do
    local x = io.read("n")
    if last ~= x then
        col[#col+1] = x
        dp[#col] = {0, 0}
        colpos[x] = colpos[x] or {head = 1}
        colpos[x][#colpos[x] + 1] = #col
        last = x
    end
end
n = #col
dp[1][1] = 1
dp[n+1] = {}
for i = 1, n do
    local x = col[i]
    local last_pos = colpos[x][colpos[x].head]
    if last_pos == i then
        dp[i][2] = dp[i][1]
    else
        dp[i][2] = dp[last_pos][2] + dp[i][1]
        dp[i][1] = dp[i][1] + dp[last_pos][2]
    end
    dp[i+1][1] = dp[i][1]

    dp[i][1] = dp[i][1] % mof
    dp[i][2] = dp[i][2] % mof
    if last_pos ~= i then
        colpos[x].head = colpos[x].head + 1
    end
    -- print(string.format("dp[%d] = {%d,%d}; col = %d", i,dp[i][1],dp[i][2], col[i]))
end
print(dp[n][1])

Score : 700 points

Problem Statement

There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i.

Snuke will perform the following operation zero or more times:

Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.

Find the number of possible final sequences of colors of the stones, modulo 10^9+7.

Constraints

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

1 \leq C_i \leq 2\times 10^5(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
C_1
:
C_N

Output

Print the number of possible final sequences of colors of the stones, modulo 10^9+7.

Sample Input 1

5
1
2
1
2
2

Sample Output 1

3

We can make three sequences of colors of stones, as follows:

(1,2,1,2,2), by doing nothing.

(1,1,1,2,2), by choosing the first and third stones to perform the operation.

(1,2,2,2,2), by choosing the second and fourth stones to perform the operation.

Sample Input 2

6
4
2
5
4
2
4

Sample Output 2

5

Sample Input 3

7
1
3
1
2
3
3
2

Sample Output 3

5


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

local dp = {}
local last_pos = {}
dp[0] = 1
for i=1,N do
    if C[i] == C[i-1] then
        -- No stone between i-1 and i
        dp[i] = dp[i-1]
    else
        local c = C[i]
        if last_pos[c] then
            -- Stones from (last_pos[c], i) are reversible.
            -- Not reverse: dp[i-1]
            -- Reverse: dp[last_pos[c]]
            dp[i] = dp[i-1] + dp[last_pos[c]]
        else
            -- Can't reverse stone because this is first appearance of c
            dp[i] = dp[i-1]
        end
        last_pos[c] = i
    end
    --print(i,C[i],dp[i])
end
print(dp[N])


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

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


n, m, c = io.read("*n", "*n", "*n")
b = {}
for i = 1, m do
  b[i] = io.read("*n")
end
r = 0
for i = 1, n do
  z = c
  for i = 1, m do
    a = io.read("*n")
    z = z + a * b[i]
  end
  if 0 < z then r = r + 1 end
end
print(r)

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


local N, M, C = io.read("n", "n", "n")
local B = {}
for i=1,M do
    table.insert(B, io.read("n"))
end
local ans = 0
for i=1,N do
    local score = C
    for j=1,M do
        score = score + io.read("n") * B[j]
    end
    if score > 0 then
        ans = ans + 1
    end
end
print(ans)


n,m=io.read("*n","*n","*l")
a={}
for i=1,n do
    a[i]={}
    a[i][1],a[i][2]=io.read("*n","*n")
end
table.sort(a,function(x,y)
    if x[1]~=y[1] then
        return x[1]<y[1]
    else
        return x[2]>y[2]
    end
end)

drink=0
yen=0
for i=1,n do
    if m-drink<a[i][2] then
        yen=yen+a[i][1]*(m-drink)
        print(yen)
        return
    else
        drink=drink+a[i][2]
        yen=yen+a[i][1]*a[i][2]
    end
end
print(yen)

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

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


local n, m = io.read("*n", "*n")
local t = {}
for i = 1, n do
  t[i] = {}
  t[i][1], t[i][2] = io.read("*n", "*n")
end
table.sort(t, function(x, y) return x[1] < y[1] end)
local ret = 0
for i = 1, n do
  if t[i][2] < m then
    m = m - t[i][2]
    ret = ret + t[i][1] * t[i][2]
  else
    ret = ret + t[i][1] * m
    m = 0
    break
  end
end
print(ret)


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

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


local s = io.read()
local t = {}
local ret = 0
local cur = 0
for i = 1, #s do
  local ss = s:sub(i, i) == "0"
  if ss then
    if cur < 0 then
      cur = cur + 1
      ret = ret + 1
    else
      cur = cur + 1
    end
  else
    if 0 < cur then
      cur = cur - 1
      ret = ret + 1
    else
      cur = cur - 1
    end
  end
end
print(ret * 2)

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


local zeroes, ones = 0, 0
while true do
    local c = io.read(1)
    if c == '0' then
        zeroes = zeroes + 1
    elseif c == '1' then
        ones = ones + 1
    elseif c == '\n' then
        break
    end
end
print(math.min(zeroes, ones) * 2)


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

function parse_problem()
    local tbl = {}
    local S = io.read("l"):gsub("[^%d]", "")
    dbgpr(S, string.len(S))
    --local S_split = {S:byte(1, S:len())}
    local cur_char = nil
    local cur_succ = nil
    for _,v in ipairs({S:byte(1, S:len())}) do
        if v ~= cur_char then
            if cur_succ ~= nil then
                table.insert(tbl, cur_succ)
            end
            cur_char = v
            cur_succ = 1
        else
            cur_succ = cur_succ + 1
        end
    end
    if cur_succ ~= nil then
        table.insert(tbl, cur_succ)
    end
    dbgpr_t(tbl)
    return tbl
end

function main()
    local tbl = parse_problem()
    local del_count = 0
    while #tbl >= 2 do
        local a, b = tbl[1], tbl[2]
        if a == b then
            del_count = del_count + a
            -- remove a, b
            table.remove(tbl, 2)
            table.remove(tbl, 1)
        elseif a > b then
            local r = a - b
            del_count = del_count + b
            -- remove b, merge r into c
            table.remove(tbl, 2)
            table.remove(tbl, 1)
            if #tbl >= 1 then
                tbl[1] = tbl[1] + r
            end
        else
            -- b > a
            local r = b - a
            del_count = del_count + a
            -- remove a
            table.remove(tbl, 1)
            -- update b
            tbl[1] = r
        end
    end
    local ans = del_count * 2
    print(ans)
end

main()


local UnionFind={}

UnionFind.create=function(self,n)
    self.par={}
    self.rank={}
    self.size={}
    for i=1,n do
        self.par[i]=i
        self.rank[i]=1
        self.size[i]=1
    end
end

UnionFind.getroot=function(self,x)
    local nx=x
    while self.par[x]~=x do
        x=self.par[x]
    end
    while self.par[nx]~=x do
        self.par[nx],nx=x,self.par[nx]
    end
    return x
end

UnionFind.same=function(self,x,y)
    return self:getroot(x)==self:getroot(y)
end

UnionFind.unite=function(self,x,y)
    x=self:getroot(x)
    y=self:getroot(y)
    if x==y then
        return
    end
    if self.rank[x]>self.rank[y] then
        x,y=y,x
    elseif self.rank[x]==self.rank[y] then
        self.rank[x]=self.rank[x]+1
    end
    self.par[x]=y
    self.size[y]=self.size[y]+self.size[x]
end

UnionFind.getsize=function(self,x)
    return self.size[self:getroot(x)]
end

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

----------

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

local t={[m]=math.floor(n*(n-1)/2)}
local uf=UnionFind:new(n)
for i=m-1,1,-1 do
    if uf:same(a[i+1],b[i+1]) then
        t[i]=t[i+1]
    else
        local ua=uf:getsize(a[i+1])
        local ub=uf:getsize(b[i+1])
        uf:unite(a[i+1],b[i+1])
        t[i]=t[i+1]-ua*ub
    end
end

for i=1,m do
    print(t[i])
end

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


local n, m = io.read("*n", "*n")
local as, bs = {}, {}
local parent = {}
local sz = {}
for i = 1, n do
  parent[i] = i
  sz[i] = 1
end
local ret = n * (n - 1) // 2
for i = 1, m do
  as[i], bs[i] = io.read("*n", "*n")
end

local function uf_findroot(idx)
  local idx_update = idx
  while parent[idx] ~= idx do
    idx, parent[idx] = parent[idx], idx_update
  end
  parent[idx_update] = idx
  return idx
end
local ans = {}
for i = 1, m do
  ans[i] = 0
end
for i = m, 1, -1 do
  ans[i] = ret
  local a, b = as[i], bs[i]
  local ra, rb = uf_findroot(a), uf_findroot(b)
  if ra ~= rb then
    local sza, szb = sz[ra], sz[rb]
    ret = ret - sza * szb
    sz[ra] = sza + szb
    parent[rb], parent[b] = ra, ra
  end
end
print(table.concat(ans, "\n"))


s = io.read():sub(6, 7)
if s == "01" or s == "02" or s == "03" or s == "04" then
  print("Heisei")
else
  print("TBD")
end

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


y,m,d = string.match(io.read(), ("(.+)/(.+)/(.+)"))
if tonumber(y)<=2019 and tonumber(m)<=4 and tonumber(d)<=30 then
    print "Heisei"
else
    print "TBD"
end


function pay(x,y,z)
    return math.abs(x-a)+math.abs(y-b)+math.abs(z-c)
end

function dfs(cur,a,b,c)
    if cur == #bamboos+1 then
        return math.min(a,b,c) > 0 and pay(a,b,c) - 30 or math.huge
    end
    local vcur = bamboos[cur]
    local toa = 10 + dfs(cur+1, a+vcur, b, c)
    local tob = 10 + dfs(cur+1, a, b+vcur, c)
    local toc = 10 + dfs(cur+1, a, b, c+vcur)
    return math.min(toa, tob, toc)
end
n, a, b, c = io.read("n", "n", "n", "n")
bamboos = {}
for i=1,n do
    bamboos[i] = io.read("n")
end
print(dfs(1,0,0,0))

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


a, b = io.read("*n", "*n")
if b % a == 0 then
  print(a + b)
else
  print(b - a)
end

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


local a, b = io.read("n","n")
if b % a == 0 then
    print(a+b)
else
    print(b-a)
end


N=io.read("n")
M=io.read("n")
k={}
A={}
t={}
for i=1,N do
  k[i]=io.read("n")
  A[i]={}
  for j=1,k[i] do
    A[i][j]=io.read("n")
    t[A[i][j]]=(t[A[i][j]] or 0)+1
  end
end
local count=0
for i,v in pairs(t) do
  if v==N then
    count=count+1
  end
end
print(count)

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3


N=string.match(io.read(),"%d+")
A={}
k=1
for i in string.gmatch(io.read(),"%d+") do
	A[k]=i
  	k=k+1
end
table.sort(A)
function mod()
    while A[#A-1]~=0 do

        local index=0
        for i=1,#A do
            if A[i]~=0 then
                if A[i]==1 then
                    return 1
                end
                index=i
                break
            end
        end
        for i=index,#A-1 do
            A[i+1]=A[i+1]%A[i]
        end
     table.sort(A)
    end
    return A[#A]
end
print(mod())

Score : 300 points

Problem Statement

There are N monsters, numbered 1, 2, ..., N.

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


function gcd(a,b)
  if a<b then
    return gcd(b,a)
  elseif a%b==0 then
    return b
  else
    return gcd(b,a%b)
  end
end
n=io.read():match("%d+")
for i in io.read():gmatch("%d+") do
  if ans==nil then
    ans=i*1
  end
  ans=gcd(ans,i*1)
end
print(string.format("%d",ans))


local n, m = io.read("*n", "*n")
local a = {}
for i = 1, 9 do a[i] = false end
local num_to_line = {2, 5, 5, 4, 5, 6, 3, 7, 6}
local topval = {0, 0, 0, 0, 0, 0, 0}
for i = 1, m do
  local tmp = io.read("*n")
  a[tmp] = true
  local line = num_to_line[tmp]
  topval[line] = math.max(topval[line], tmp)
end
local r = {}
local ins = table.insert
if a[1] then
  if n % 2 == 1 then
    local tmp = {7, 5, 3, 2, 8}
    for i = 1, 5 do
      if a[tmp[i]] then
        ins(r, tmp[i])
        n = n - num_to_line[tmp[i]]
        break
      end
    end
  end
  for i = 1, n / 2 do ins(r, 1) end
elseif a[7] then
  if n % 3 == 1 then
    if a[4] then ins(r, 4) n = n - 4
    elseif a[8] then ins(r, 8) n = n - 7
    else ins(r, topval[5]) ins(r, topval[5]) n = n - 10
    end
  elseif n % 3 == 2 then
    if 0 < topval[5] then ins(r, topval[5]) n = n - 5
    elseif a[4] then ins(r, 4) ins(r, 4) n = n - 8
    else ins(r, 8) ins(r, 8) n = n - 14
    end
  end
  for i = 1, n / 3 do ins(r, 7) end
elseif a[4] then
  if n % 4 == 1 then
    if 0 < topval[5] then ins(r, topval[5]) n = n - 5
    elseif 0 < topval[6] then ins(r, topval[6]) ins(r, 8) n = n - 13
    else ins(r, 8) ins(r, 8) ins(r, 8) n = n - 21
    end
  elseif n % 4 == 2 then
    if 0 < topval[6] then ins(r, topval[6]) n = n - 6
    elseif 0 < topval[5] then ins(r, topval[5]) ins(r, topval[5]) n = n - 10
    else ins(r, 8) ins(r, 8) n = n - 14
    end
  elseif n % 4 == 3 then
    if a[9] and 0 < topval[5] then ins(r, 9) ins(r, topval[5]) n = n - 11
    elseif a[8] then ins(r, 8) n = n - 7
    elseif a[6] then ins(r, 6) ins(r, topval[5]) n = n - 11
    else ins(r, topval[5]) ins(r, topval[5]) ins(r, topval[5]) n = n - 15
    end
  end
  for i = 1, n / 4 do ins(r, 4) end
elseif 0 < topval[5] then
  if n % 5 == 1 then
    if 0 < topval[6] then ins(r, topval[6]) n = n - 6
    else ins(r, 8) ins(r, 8) ins(r, 8) n = n - 21
    end
  elseif n % 5 == 2 then
    if a[9] then ins(r, 9) ins(r, 9) n = n - 12
    elseif a[8] then ins(r, 8) n = n - 7
    else ins(r, 6) ins(r, 6) n = n - 12
    end
  elseif n % 5 == 3 then
    if 0 < topval[6] and a[8] then ins(r, topval[6]) ins(r, 8) n = n - 13
    elseif 0 < topval[6] then ins(r, topval[6]) ins(r, topval[6]) ins(r, topval[6]) n = n - 18
    else ins(r, 8) ins(r, 8) ins(r, 8) ins(r, 8) n = n - 28
    end
  elseif n % 5 == 4 then
    if a[9] then
      for i = 1, 4 do ins(r, 9) end
      n = n - 24
    elseif a[8] then ins(r, 8) ins(r, 8) n = n - 14
    else
      for i = 1, 4 do ins(r, 6) end
      n = n - 24
    end
  end
  for i = 1, n / 5 do ins(r, topval[5]) end
elseif 0 < topval[6] then
  for i = 1, n % 6 do ins(r, 8) end
  n = n - 7 * (n % 6)
  for i = 1, n / 6 do ins(r, topval[6]) end
else
  for i = 1, n / 7 do ins(r, 8) end
end
table.sort(r, function(a, b) return a > b end)
print(table.concat(r, ""))

Score : 400 points

Problem Statement

Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:

Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).

The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectively.

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

There exists an integer that can be formed by exactly N matchsticks under the conditions.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

Print the largest integer that can be formed with exactly N matchsticks under the conditions in the problem statement.

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

The integer 777773 can be formed with 3 + 3 + 3 + 3 + 3 + 5 = 20 matchsticks, and this is the largest integer that can be formed by 20 matchsticks under the conditions.

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

The output may not fit into a 64-bit integer type.

Sample Input 3

15 3
5 4 6

Sample Output 3

654


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

if b-a<=2 then
    print(k+1)
else
    if k-(a-1)>=2 then
        x=(k-(a-1))//2
        y=(k-(a-1))%2
        print(a+(b-a)*x+y)
    else
        print(k+1)
    end
end

Score : 400 points

Problem Statement

Snuke has one biscuit and zero Japanese yen (the currency) in his pocket.
He will perform the following operations exactly K times in total, in the order he likes:

Hit his pocket, which magically increases the number of biscuits by one.

Exchange A biscuits to 1 yen.

Exchange 1 yen to B biscuits.

Find the maximum possible number of biscuits in Snuke's pocket after K operations.

Constraints

1 \leq K,A,B \leq 10^9

K,A and B are integers.

Input

Input is given from Standard Input in the following format:

K A B

Output

Print the maximum possible number of biscuits in Snuke's pocket after K operations.

Sample Input 1

4 2 6

Sample Output 1

7

The number of biscuits in Snuke's pocket after K operations is maximized as follows:

Hit his pocket. Now he has 2 biscuits and 0 yen.

Exchange 2 biscuits to 1 yen. his pocket. Now he has 0 biscuits and 1 yen.

Hit his pocket. Now he has 1 biscuits and 1 yen.

Exchange 1 yen to 6 biscuits. his pocket. Now he has 7 biscuits and 0 yen.

Sample Input 2

7 3 4

Sample Output 2

8

Sample Input 3

314159265 35897932 384626433

Sample Output 3

48518828981938099


Score : 100 points

Problem Statement

In order to pass the entrance examination tomorrow, Taro has to study for T more hours.

Fortunately, he can leap to World B where time passes X times as fast as it does in our world (World A).

While (X \times t) hours pass in World B, t hours pass in World A.

How many hours will pass in World A while Taro studies for T hours in World B?

Constraints

All values in input are integers.

1 \leq T \leq 100

1 \leq X \leq 100

Input

Input is given from Standard Input in the following format:

T X

Output

Print the number of hours that will pass in World A.

The output will be regarded as correct when its absolute or relative error from the judge's output is at most 10^{-3}.

Sample Input 1

8 3

Sample Output 1

2.6666666667

While Taro studies for eight hours in World B where time passes three times as fast, 2.6666... hours will pass in World A.

Note that an absolute or relative error of at most 10^{-3} is allowed.

Sample Input 2

99 1

Sample Output 2

99.0000000000

Sample Input 3

1 100

Sample Output 3

0.0100000000