function dp(point, visited, vertexes, memo)
  if not string.find(visited, "0") then
    return 1
  elseif memo[point][visited] then
    return memo[point][visited]
  else
    local ans = 0
    for i = 1, #vertexes[point] do
      if string.sub(visited, vertexes[point][i], vertexes[point][i]) == "0" then
        ans = ans + dp(vertexes[point][i], string.sub(visited, 1, vertexes[point][i] - 1) .. "1" .. string.sub(visited, vertexes[point][i] + 1, #visited), vertexes, memo)
      end
    end
    memo[point][visited] = ans
    return ans
  end
end

function main()
  local input = string.gmatch(io.read(), "[^ ]+")
  local n = tonumber(input())
  local m = tonumber(input())

  local vertexes = {}
  local memo = {}
  for i = 1, n do
    table.insert(vertexes, {})
    table.insert(memo, {})
  end

  for i = 1, m do
    input = string.gmatch(io.read(), "[^ ]+")
    local a = tonumber(input())
    local b = tonumber(input())
    table.insert(vertexes[a], b)
    table.insert(vertexes[b], a)
  end

  local visited = "1"
  for i = 2, n do
    visited = visited .. "0"
  end

  print(dp(1, visited, vertexes, memo))
end

main()

Score : 300 points

Problem Statement

You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

How many different paths start from vertex 1 and visit all the vertices exactly once?

Here, the endpoints of a path are considered visited.

For example, let us assume that the following undirected graph shown in Figure 1 is given.

Figure 1: an example of an undirected graph

The following path shown in Figure 2 satisfies the condition.

Figure 2: an example of a path that satisfies the condition

However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.

Figure 3: an example of a path that does not satisfy the condition

Neither the following path shown in Figure 4, because it does not start from vertex 1.

Figure 4: another example of a path that does not satisfy the condition

Constraints

2≦N≦8

0≦M≦N(N-1)/2

1≦a_i<b_i≦N

The given graph contains neither self-loops nor double edges.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once.

Sample Input 1

3 3
1 2
1 3
2 3

Sample Output 1

2

The given graph is shown in the following figure:

The following two paths satisfy the condition:

Sample Input 2

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

Sample Output 2

1

This test case is the same as the one described in the problem statement.


local mmi, mma = math.min, math.max
local n, ma, mb = io.read("*n", "*n", "*n")
local a, b, c = {}, {}, {}
for i = 1, n do
  a[i], b[i], c[i] = io.read("*n", "*n", "*n")
end
local inf = 1000000007
local t = {}
for i = 1, 400 do
  t[i] = {}
  for j = 1, 400 do
    t[i][j] = inf
  end
end
for k = 1, n do
  for i = 400 - a[k], 1, -1 do
    for j = 400 - b[k], 1, -1 do
      t[i + a[k]][j + b[k]] = mmi(t[i + a[k]][j + b[k]], t[i][j] + c[k])
    end
  end
  t[a[k]][b[k]] = mmi(t[a[k]][b[k]], c[k])
end
local ret = -1
for i = 1, 400 do
  for j = 1, 400 do
    if i * mb == j * ma and t[i][j] < inf then
      if ret < 0 or t[i][j] < ret then
        ret = t[i][j]
      end
    end
  end
end
print(ret)

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

Score : 400 points

Problem Statement

Dolphin is planning to generate a small amount of a certain chemical substance C.

In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b.

He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmacy.

The pharmacy sells N kinds of chemicals. For each kind of chemical, there is exactly one package of that chemical in stock.

The package of chemical i contains a_i grams of the substance A and b_i grams of the substance B, and is sold for c_i yen (the currency of Japan).

Dolphin will purchase some of these packages. For some reason, he must use all contents of the purchased packages to generate the substance C.

Find the minimum amount of money required to generate the substance C.

If it is not possible to generate the substance C by purchasing any combination of packages at the pharmacy, report that fact.

Constraints

1≦N≦40

1≦a_i,b_i≦10

1≦c_i≦100

1≦M_a,M_b≦10

gcd(M_a,M_b)=1

a_i, b_i, c_i, M_a and M_b are integers.

Input

The input is given from Standard Input in the following format:

N M_a M_b
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the minimum amount of money required to generate the substance C. If it is not possible to generate the substance C, print -1 instead.

Sample Input 1

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

Sample Output 1

3

The amount of money spent will be minimized by purchasing the packages of chemicals 1 and 2.

In this case, the mixture of the purchased chemicals will contain 3 grams of the substance A and 3 grams of the substance B, which are in the desired ratio: 3:3=1:1.

The total price of these packages is 3 yen.

Sample Input 2

1 1 10
10 10 10

Sample Output 2

-1

The ratio 1:10 of the two substances A and B cannot be satisfied by purchasing any combination of the packages. Thus, the output should be -1.

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 mma = math.max
local mfl, mce, mmi = math.floor, math.ceil, math.min

local n = io.read("*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
if n == 1 then print("YES") os.exit() end

local sum = 0
local mod = mfl(n * (n + 1) / 2)
local cnt = 0
for i = 1, n do
  cnt = cnt + mfl((sum + a[i]) / mod)
  sum = (sum + a[i]) % mod
end
if sum ~= 0 then print("NO") os.exit() end

local b = {}
for i = 1, n - 1 do
  b[i] = a[i + 1] - a[i]
end
b[n] = a[1] - a[n]

for i = 1, n do
  b[i] = b[i] - cnt
end

for i = 1, n do
  if 0 < b[i] then cnt = -1 break end
  local v = -b[i]
  if v % n ~= 0 then cnt = -1 break end
  cnt = cnt - mfl(v / n)
end
print(cnt == 0 and "YES" or "NO")

Score : 500 points

Problem Statement

There are N boxes arranged in a circle. The i-th box contains A_i stones.

Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation:

Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-th box. Here, the (N+k)-th box is identified with the k-th box.

Note that the operation cannot be performed if there is a box that does not contain enough number of stones to be removed.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N

Output

If it is possible to remove all the stones from the boxes, print YES. Otherwise, print NO.

Sample Input 1

5
4 5 1 2 3

Sample Output 1

YES

All the stones can be removed in one operation by selecting the second box.

Sample Input 2

5
6 9 12 10 8

Sample Output 2

YES

Sample Input 3

4
1 2 3 1

Sample Output 3

NO


local mma = math.max
local mfl, mce, mmi = math.floor, math.ceil, math.min

local AvlTree = {}
AvlTree.makenode = function(self, val, parent)
  local i = self.box[#self.box]
  if not i then i = #self.v + 1
  else table.remove(self.box)
  end
  self.v[i], self.p[i] = val, parent
  self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  return i
end
AvlTree.create = function(self, lessthan, n)
  self.lessthan = lessthan
  self.root = 1
  self.box = {}
  for i = n + 1, 2, -1 do table.insert(self.box, i) end
  -- value, leftCount, rightCount, left, right, parent
  self.v, self.lc, self.rc, self.l, self.r, self.p = {}, {}, {}, {}, {}, {}
  for i = 1, n + 1 do
    self.v[i], self.p[i] = 0, 1
    self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  end
end

AvlTree.recalc = function(self, i)
  local kl, kr = self.l[i], self.r[i]
  if 1 < kl then self.lc[i] = 1 + mma(self.lc[kl], self.rc[kl])
  else self.lc[i] = 0
  end
  if 1 < kr then self.rc[i] = 1 + mma(self.lc[kr], self.rc[kr])
  else self.rc[i] = 0
  end
end
AvlTree.recalcAll = function(self, i)
  while 1 < i do
    self:recalc(i)
    i = self.p[i]
  end
end

AvlTree.rotR = function(self, parent)
  local granp, child = self.p[parent], self.l[parent]
  self.r[child], self.l[parent] = parent, self.r[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.l[parent]] = parent
  if 1 < granp then
    if self.l[granp] == parent then
      self.l[granp] = child
    else
      self.r[granp] = child
    end
  else
    self.root = child
  end
end

AvlTree.rotL = function(self, parent)
  local granp, child = self.p[parent], self.r[parent]
  self.l[child], self.r[parent] = parent, self.l[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.r[parent]] = parent
  if 1 < granp then
    if self.r[granp] == parent then
      self.r[granp] = child
    else
      self.l[granp] = child
    end
  else
    self.root = child
  end
end

AvlTree.rotLR = function(self, lparent, rparent)
  local sp, sl, sr = self.p, self.l, self.r
  local granp, d = sp[rparent], sr[lparent]
  sp[lparent], sr[lparent] = d, sl[d]
  sp[rparent], sl[rparent] = d, sr[d]
  sp[sl[d]], sp[sr[d]] = lparent, rparent
  sp[d], sl[d], sr[d] = granp, lparent, rparent
  if 1 < granp then
    if sr[granp] == rparent then sr[granp] = d
    else sl[granp] = d
    end
  else self.root = d
  end
end

AvlTree.rotRL = function(self, rparent, lparent)
  local sp, sl, sr = self.p, self.l, self.r
  local granp, d = sp[lparent], sl[rparent]
  sp[rparent], sl[rparent] = d, sr[d]
  sp[lparent], sr[lparent] = d, sl[d]
  sp[sr[d]], sp[sl[d]] = rparent, lparent
  sp[d], sr[d], sl[d] = granp, rparent, lparent
  if 1 < granp then
    if sl[granp] == lparent then sl[granp] = d
    else sr[granp] = d
    end
  else self.root = d
  end
end

AvlTree.push = function(self, val)
  if self.root <= 1 then self.root = self:makenode(val, 1) return end
  local pos = self.root
  while true do
    if self.lessthan(val, self.v[pos]) then
      if 1 < self.l[pos] then
        pos = self.l[pos]
      else
        self.l[pos] = self:makenode(val, pos)
        pos = self.l[pos]
        break
      end
    else
      if 1 < self.r[pos] then
        pos = self.r[pos]
      else
        self.r[pos] = self:makenode(val, pos)
        pos = self.r[pos]
        break
      end
    end
  end
  while 1 < pos do
    local child, parent = pos, self.p[pos]
    if parent <= 1 then
      break
    end
    self:recalc(parent)
    local lcp_m_rcp = self.lc[parent] - self.rc[parent]
    if lcp_m_rcp % 2 ~= 0 then -- 1 or -1
      pos = parent
    elseif lcp_m_rcp == 2 then
      if self.lc[child] - 1 == self.rc[child] then
        self:rotR(parent)
        self:recalcAll(parent)
      else
        self:rotLR(child, parent)
        self:recalc(child)
        self:recalcAll(parent)
      end
      break
    elseif lcp_m_rcp == -2 then
      if self.rc[child] - 1 == self.lc[child] then
        self:rotL(parent)
        self:recalcAll(parent)
      else
        self:rotRL(child, parent)
        self:recalc(child)
        self:recalcAll(parent)
      end
      break
    else
      break
    end
  end
end

AvlTree.rmsub = function(self, node)
  while 1 < node do
    self:recalc(node)
    if self.lc[node] == self.rc[node] then
      node = self.p[node]
    elseif self.lc[node] + 1 == self.rc[node] then
      self:recalcAll(self.p[node])
      break
    else
      if self.lc[self.r[node]] == self.rc[self.r[node]] then
        self:rotL(node)
        self:recalcAll(node)
        break
      elseif self.lc[self.r[node]] + 1 == self.rc[self.r[node]] then
        local nr = self.r[node]
        self:rotL(node)
        self:recalc(node)
        node = nr
      else
        local nr = self.r[node]
        local nrl = self.l[nr]
        self:rotRL(nr, node)
        self:recalc(nr)
        self:recalc(node)
        node = nrl
      end
    end
  end
end

AvlTree.pop = function(self)
  local node = self.root
  while 1 < self.l[node] do
    node = self.l[node]
  end
  local v = self.v[node]
  local kp = self.p[node]
  self.p[self.r[node]] = kp
  if 1 < kp then
    self.l[kp] = self.r[node]
    self:rmsub(kp)
  else
    self.root = self.r[node]
  end
  table.insert(self.box, node)
  return v
end

AvlTree.top = function(self)
  local node = self.root
  while 1 < self.l[node] do
    node = self.l[node]
  end
  return self.v[node]
end

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

local n = io.read("*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
if n == 1 then print("YES") os.exit() end
local b = {}
for i = 1, n - 1 do
  b[i] = a[i + 1] - a[i]
end
b[n] = a[1] - a[n]

local avl = AvlTree.new(function(x, y) return b[x] < b[y] end, n)
local cnt = 0
local asked = {}
for i = 1, n do
  asked[i] = false
  avl:push(i)
end
while true do
  local p = avl:pop()
  if asked[p] then break end
  asked[p] = true
  local next_top = avl:top()
  if b[p] < cnt then
    local addcnt = mce((cnt - b[p]) / (n - 1))
    b[p] = b[p] + addcnt * n
    cnt = cnt + addcnt
    avl:push(p)
  else
    break
  end
end
local valid = true
for i = 1, n do
  if cnt ~= b[i] then
    valid = false
    break
  end
end
print(valid and "YES" or "NO")


local mma = math.max
local mfl, mce, mmi = math.floor, math.ceil, math.min

local AvlTree = {}
AvlTree.makenode = function(self, val, parent)
  local i = self.box[#self.box]
  if not i then i = #self.v + 1
  else table.remove(self.box)
  end
  self.v[i], self.p[i] = val, parent
  self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  return i
end
AvlTree.create = function(self, lessthan, n)
  self.lessthan = lessthan
  self.root = 1
  self.box = {}
  for i = n + 1, 2, -1 do table.insert(self.box, i) end
  -- value, leftCount, rightCount, left, right, parent
  self.v, self.lc, self.rc, self.l, self.r, self.p = {}, {}, {}, {}, {}, {}
  for i = 1, n + 1 do
    self.v[i], self.p[i] = 0, 1
    self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  end
end

AvlTree.recalc = function(self, i)
  local kl, kr = self.l[i], self.r[i]
  if 1 < kl then self.lc[i] = 1 + mma(self.lc[kl], self.rc[kl])
  else self.lc[i] = 0
  end
  if 1 < kr then self.rc[i] = 1 + mma(self.lc[kr], self.rc[kr])
  else self.rc[i] = 0
  end
end
AvlTree.recalcAll = function(self, i)
  while 1 < i do
    self:recalc(i)
    i = self.p[i]
  end
end

AvlTree.rotR = function(self, parent)
  local granp, child = self.p[parent], self.l[parent]
  self.r[child], self.l[parent] = parent, self.r[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.l[parent]] = parent
  if 1 < granp then
    if self.l[granp] == parent then
      self.l[granp] = child
    else
      self.r[granp] = child
    end
  else
    self.root = child
  end
end

AvlTree.rotL = function(self, parent)
  local granp, child = self.p[parent], self.r[parent]
  self.l[child], self.r[parent] = parent, self.l[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.r[parent]] = parent
  if 1 < granp then
    if self.r[granp] == parent then
      self.r[granp] = child
    else
      self.l[granp] = child
    end
  else
    self.root = child
  end
end

AvlTree.rotLR = function(self, lparent, rparent)
  local sp, sl, sr = self.p, self.l, self.r
  local granp, d = sp[rparent], sr[lparent]
  sp[lparent], sr[lparent] = d, sl[d]
  sp[rparent], sl[rparent] = d, sr[d]
  sp[sl[d]], sp[sr[d]] = lparent, rparent
  sp[d], sl[d], sr[d] = granp, lparent, rparent
  if 1 < granp then
    if sr[granp] == rparent then sr[granp] = d
    else sl[granp] = d
    end
  else self.root = d
  end
end

AvlTree.rotRL = function(self, rparent, lparent)
  local sp, sl, sr = self.p, self.l, self.r
  local granp, d = sp[lparent], sl[rparent]
  sp[rparent], sl[rparent] = d, sr[d]
  sp[lparent], sr[lparent] = d, sl[d]
  sp[sr[d]], sp[sl[d]] = rparent, lparent
  sp[d], sr[d], sl[d] = granp, rparent, lparent
  if 1 < granp then
    if sl[granp] == lparent then sl[granp] = d
    else sr[granp] = d
    end
  else self.root = d
  end
end

AvlTree.push = function(self, val)
  if self.root <= 1 then self.root = self:makenode(val, 1) return end
  local pos = self.root
  while true do
    if self.lessthan(val, self.v[pos]) then
      if 1 < self.l[pos] then
        pos = self.l[pos]
      else
        self.l[pos] = self:makenode(val, pos)
        pos = self.l[pos]
        break
      end
    else
      if 1 < self.r[pos] then
        pos = self.r[pos]
      else
        self.r[pos] = self:makenode(val, pos)
        pos = self.r[pos]
        break
      end
    end
  end
  while 1 < pos do
    local child, parent = pos, self.p[pos]
    if parent <= 1 then
      break
    end
    self:recalc(parent)
    local lcp_m_rcp = self.lc[parent] - self.rc[parent]
    if lcp_m_rcp % 2 ~= 0 then -- 1 or -1
      pos = parent
    elseif lcp_m_rcp == 2 then
      if self.lc[child] - 1 == self.rc[child] then
        self:rotR(parent)
        self:recalcAll(parent)
      else
        self:rotLR(child, parent)
        self:recalc(child)
        self:recalcAll(parent)
      end
      break
    elseif lcp_m_rcp == -2 then
      if self.rc[child] - 1 == self.lc[child] then
        self:rotL(parent)
        self:recalcAll(parent)
      else
        self:rotRL(child, parent)
        self:recalc(child)
        self:recalcAll(parent)
      end
      break
    else
      break
    end
  end
end

AvlTree.rmsub = function(self, node)
  while 1 < node do
    self:recalc(node)
    if self.lc[node] == self.rc[node] then
      node = self.p[node]
    elseif self.lc[node] + 1 == self.rc[node] then
      self:recalcAll(self.p[node])
      break
    else
      if self.lc[self.r[node]] == self.rc[self.r[node]] then
        self:rotL(node)
        self:recalcAll(node)
        break
      elseif self.lc[self.r[node]] + 1 == self.rc[self.r[node]] then
        local nr = self.r[node]
        self:rotL(node)
        self:recalc(node)
        node = nr
      else
        local nr = self.r[node]
        local nrl = self.l[nr]
        self:rotRL(nr, node)
        self:recalc(nr)
        self:recalc(node)
        node = nrl
      end
    end
  end
end

AvlTree.pop = function(self)
  local node = self.root
  while 1 < self.l[node] do
    node = self.l[node]
  end
  local v = self.v[node]
  local kp = self.p[node]
  self.p[self.r[node]] = kp
  if 1 < kp then
    self.l[kp] = self.r[node]
    self:rmsub(kp)
  else
    self.root = self.r[node]
  end
  table.insert(self.box, node)
  return v
end

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

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

local avl = AvlTree.new(function(x, y) return b[x] < b[y] end, n)
local cnt = 0
local asked = {}
for i = 1, n do
  asked[i] = false
  avl:push(i)
end
while true do
  local p = avl:pop()
  if asked[p] then break end
  asked[p] = true
  if b[p] < cnt then
    b[p] = b[p] + n
    cnt = cnt + 1
    avl:push(p)
  else
    break
  end
end
local valid = true
for i = 1, n do
  if cnt ~= b[i] then
    valid = false
    break
  end
end
print(valid and "YES" or "NO")


a=io.read()*1
print(a<1200 and "ABC" or "ARC")

Score : 100 points

Problem Statement

Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.

You are given Smeke's current rating, x. Print ABC if Smeke will participate in ABC, and print ARC otherwise.

Constraints

1 ≦ x ≦ 3{,}000

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

1000

Sample Output 1

ABC

Smeke's current rating is less than 1200, thus the output should be ABC.

Sample Input 2

2000

Sample Output 2

ARC

Smeke's current rating is not less than 1200, thus the output should be ARC.


Score : 300 points

Problem Statement

Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.

Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:

Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.

For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward.
Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.

Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.

Constraints

1 ≦ x ≦ 10^{15}

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801


x=io.read("*n")
c=x*2//11
if 1<=x%11 then
    c=c+(x%11<=6 and 1 or 2)
end
print(c)


local mfl = math.floor
local n, m = io.read("*n", "*n")
local imos = {}
for i = 1, m + 1 do
  imos[i] = 0
end
for i_n = 1, n do
  local l, r = io.read("*n", "*n")
  if l == r then
    local lim = math.ceil(math.sqrt(r))
    for i = 1, lim do
      if r % i == 0 then
        local z = mfl(r / i)
        if i <= z then
          imos[i] = imos[i] + 1
          imos[i + 1] = imos[i + 1] - 1
          if i ~= z then
            imos[z] = imos[z] + 1
            imos[z + 1] = imos[z + 1] - 1
          end
        end
      end
    end
  else
    l = l - 1
    imos[1] = imos[1] + 1
    imos[r + 1] = imos[r + 1] - 1
    for i = 1, r do
      local rlim2 = mfl(r / (i + 1))
      local llim = mfl(l / i)
      if rlim2 < llim then
        imos[rlim2 + 1] = imos[rlim2 + 1] - 1
        imos[llim + 1] = imos[llim + 1] + 1
      else
        if llim <=  r - l then
          break
        end
      end
    end
  end
end
for i = 2, m do
  imos[i] = imos[i] + imos[i - 1]
end
imos[m + 1] = nil
print(table.concat(imos, "\n"))

Score : 700 points

Problem Statement

Snuke has decided to play a game, where the player runs a railway company.
There are M+1 stations on Snuke Line, numbered 0 through M.
A train on Snuke Line stops at station 0 and every d-th station thereafter, where d is a predetermined constant for each train.
For example, if d = 3, the train stops at station 0, 3, 6, 9, and so forth.

There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind of souvenirs can be purchased when the train stops at one of the following stations: stations l_i, l_i+1, l_i+2, ..., r_i.

There are M values of d, the interval between two stops, for trains on Snuke Line: 1, 2, 3, ..., M.
For each of these M values, find the number of the kinds of souvenirs that can be purchased if one takes a train with that value of d at station 0.
Here, assume that it is not allowed to change trains.

Constraints

1 ≦ N ≦ 3 × 10^{5}

1 ≦ M ≦ 10^{5}

1 ≦ l_i ≦ r_i ≦ M

Input

The input is given from Standard Input in the following format:

N M
l_1 r_1
:
l_{N} r_{N}

Output

Print the answer in M lines. The i-th line should contain the maximum number of the kinds of souvenirs that can be purchased if one takes a train stopping every i-th station.

Sample Input 1

3 3
1 2
2 3
3 3

Sample Output 1

3
2
2

If one takes a train stopping every station, three kinds of souvenirs can be purchased: kind 1, 2 and 3.

If one takes a train stopping every second station, two kinds of souvenirs can be purchased: kind 1 and 2.

If one takes a train stopping every third station, two kinds of souvenirs can be purchased: kind 2 and 3.

Sample Input 2

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

Sample Output 2

7
6
6
5
4
5
5
3
2


local mfl = math.floor
local n, m = io.read("*n", "*n")
local imos = {}
for i = 1, m + 1 do
  imos[i] = 0
end
for i_n = 1, n do
  local l, r = io.read("*n", "*n")
  l = l - 1
  imos[1] = imos[1] + 1
  imos[r + 1] = imos[r + 1] - 1
  for i = 1, r do
    local rlim2 = mfl(r / (i + 1))
    local llim = mfl(l / i)
    if rlim2 < llim then
      imos[rlim2 + 1] = imos[rlim2 + 1] - 1
      imos[llim + 1] = imos[llim + 1] + 1
    else
      if llim <  r - l then
        break
      end
    end
  end
end
for i = 2, m do
  imos[i] = imos[i] + imos[i - 1]
end
imos[m + 1] = nil
print(table.concat(imos, "\n"))


N = io.read("*n")
S = io.read()
x = 0
y = 0
for i = 1, N do
    if S[i] == "I" then
        y = y+1
    else
        y = y-1
    end
    x = math.max(x, y)
end
print(x)

Score : 200 points

Problem Statement

You have an integer variable x.
Initially, x=0.

Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.

Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).

Constraints

1≤N≤100

|S|=N

No characters except I and D occur in S.

Input

The input is given from Standard Input in the following format:

N
S

Output

Print the maximum value taken by x during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value x=0 is the maximum value taken by x, thus the output should be 0.


N = io.read("*n")
S = io.read()
x = 0
for i = 1, N do
    if S[i] == "I" then
        x = x+1
    else
        x = x-1
    end
end
print(x)


N, S = io.read("*n", "*n")
x = 0
for i = 1, N do
    if S[i] == "I" then
        x = x+1
    else
        x = x-1
    end
end
print(x)


local n = io.read("*n")
local t = {}
for i = 2, n do
  local sqi = math.floor(math.sqrt(i)) + 1
  local j, tmpi = 2, i
  while(j <= sqi) do
    if(tmpi % j == 0) then
      tmpi = tmpi / j
      if(t[j] == nil) then t[j] = 1 else t[j] = t[j] + 1 end
    else
      if(j == 2) then j = 3 else j = j + 2 end
    end
  end
  if(tmpi ~= 1) then
    if(t[tmpi] == nil) then t[tmpi] = 1 else t[tmpi] = t[tmpi] + 1 end
  end
end
local mod = 1000000007
local ret = 1
for k, v in pairs(t) do
  ret = (ret * (v + 1)) % mod
end
print(ret)

Score : 300 points

Problem Statement

You are given an integer N.
Find the number of the positive divisors of N!, modulo 10^9+7.

Constraints

1≤N≤10^3

Input

The input is given from Standard Input in the following format:

N

Output

Print the number of the positive divisors of N!, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

4

There are four divisors of 3! =6: 1, 2, 3 and 6. Thus, the output should be 4.

Sample Input 2

6

Sample Output 2

30

Sample Input 3

1000

Sample Output 3

972926972


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

local n, m = io.read("*n", "*n", "*l")
local pos = {0}
do
  local s = io.read()
  local i = 1
  for d in s:gmatch("%d+") do
    pos[i + 1] = pos[i] + tonumber(d)
    i = i + 1
  end
end
local imos = {}
for i = 1, n do
  imos[i] = {}
  for j = i, n do
    imos[i][j - i + 1] = 0
  end
end
local t = {}

for i = 1, m do
  t[i] = {}
end
for i = 1, n do
  local s = io.read()
  local j = 1
  for d in s:gmatch("%d+") do
    t[j][i] = tonumber(d)
    j = j + 1
  end
end
local idx = {}
for i = 1, n do idx[i] = i end

local st = SegTree.new(n, mma, 0)
local stend = st.stage[st.stagenum]
for i = 1, m do
  table.sort(idx, function(a, b) return t[i][a] < t[i][b] end)
  for j = 1, n do
    stend[idx[j]] = j
  end
  st:updateAll()
  for j = 1, n - 1 do
    local tj = t[i][j]
    local rk = stend[j]
    local right = st:right_bound(rk + 1, j + 1, n) - 1
    local left = j == 1 and 1 or st:left_bound(rk + 1, 1, j - 1) + 1
    imos[left][j - left + 1] = imos[left][j - left + 1] + tj
    imos[j + 1][1] = imos[j + 1][1] - tj
    if right < n then
      imos[left][right - left + 2] = imos[left][right - left + 2] - tj
      imos[j + 1][right + 1 - j] = imos[j + 1][right + 1 - j] + tj
    end
  end
  do
    local tj = t[i][n]
    local rk = stend[n]
    local left = st:left_bound(rk + 1, 1, n - 1) + 1
    imos[left][n - left + 1] = imos[left][n - left + 1] + tj
  end
end
for i = 1, n do
  for j = 2, n - i + 1 do
    imos[i][j] = imos[i][j] + imos[i][j - 1]
  end
end
for i = 2, n do
  for j = 1, n - i + 1 do
    imos[i][j] = imos[i][j] + imos[i - 1][j + 1]
  end
end

local score = 0
for i = 1, n do
  local imi, posi = imos[i], pos[i]
  for j = i, n do
    score = mma(score, imi[j - i + 1] - pos[j] + posi)
  end
end
print(score)

Score : 1000 points

Problem Statement

There are N barbecue restaurants along a street.
The restaurants are numbered 1 through N from west to east, and the distance between restaurant i and restaurant i+1 is A_i.

Joisino has M tickets, numbered 1 through M.
Every barbecue restaurant offers barbecue meals in exchange for these tickets.
Restaurant i offers a meal of deliciousness B_{i,j} in exchange for ticket j.
Each ticket can only be used once, but any number of tickets can be used at a restaurant.

Joisino wants to have M barbecue meals by starting from a restaurant of her choice, then repeatedly traveling to another barbecue restaurant and using unused tickets at the restaurant at her current location.
Her eventual happiness is calculated by the following formula: "(The total deliciousness of the meals eaten) - (The total distance traveled)".
Find her maximum possible eventual happiness.

Constraints

All input values are integers.

2≤N≤5×10^3

1≤M≤200

1≤A_i≤10^9

1≤B_{i,j}≤10^9

Input

The input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_{N-1}
B_{1,1} B_{1,2} ... B_{1,M}
B_{2,1} B_{2,2} ... B_{2,M}
:
B_{N,1} B_{N,2} ... B_{N,M}

Output

Print Joisino's maximum possible eventual happiness.

Sample Input 1

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

Sample Output 1

11

The eventual happiness can be maximized by the following strategy: start from restaurant 1 and use tickets 1 and 3, then move to restaurant 2 and use tickets 2 and 4.

Sample Input 2

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

Sample Output 2

20


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

local n, m = io.read("*n", "*n")
local pos = {0}
for i = 1, n - 1 do
  pos[i + 1] = pos[i] + io.read("*n")
end
local imos = {}
for i = 1, n + 1 do
  imos[i] = {}
  for j = 1, n + 1 do
    imos[i][j] = 0
  end
end
local t = {}
local st = SegTree.new(n, mma, 0)

for i = 1, n do
  t[i] = {}
  for j = 1, m do
    t[i][j] = io.read("*n")
  end
end
local inf = 1000000007
local idx = {}
for i = 1, n do idx[i] = i end
for i = 1, m do
  for j = 1, n do
    st:setValue(j, t[j][i], true)
  end
  st:updateAll()
  table.sort(idx, function(a, b) return t[a][i] > t[b][i] end)
  for idxj = 1, n do
    local j = idx[idxj]
    local tj = t[j][i]
    local right = j == n and n or st:right_bound(tj + 1, j + 1, n) - 1
    local left = j == 1 and 1 or st:left_bound(tj + 1, 1, j - 1) + 1
    st:setValue(j, inf)
    imos[left][j] = imos[left][j] + tj
    imos[left][right + 1] = imos[left][right + 1] - tj
    imos[j + 1][j] = imos[j + 1][j] - tj
    imos[j + 1][right + 1] = imos[j + 1][right + 1] + tj
  end
end
for j = 1, n do
  for i = 2, n do
    imos[i][j] = imos[i][j] + imos[i - 1][j]
  end
end
for i = 1, n do
  for j = 2, n do
    imos[i][j] = imos[i][j] + imos[i][j - 1]
  end
end

local score = 0
for i = 1, n do
  for j = i, n do
    score = mma(score, imos[i][j] - pos[j] + pos[i])
  end
end
print(score)


local function uf_initialize(n)
  local parent = {}
  for i = 1, n do parent[i] = i end
  return parent
end

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

local function kruskal(n, line)
  -- line.c, line.i1, line.i2
  table.sort(line, function(a, b) return a.c < b.c end)
  local parent = uf_initialize(n)
  local totalcost = 0
  local used = 0
  local linenum = #line
  for i = 1, linenum do
    local c, i1, i2 = line[i].c, line[i].i1, line[i].i2
    local r1, r2 = uf_findroot(i1, parent), uf_findroot(i2, parent)
    parent[i1], parent[i2] = r1, r2
    if r1 ~= r2 then
      parent[r2] = r1
      parent[i2] = r1
      totalcost = totalcost + c
      used = used + 1
      if used == n - 1 then break end
    end
  end
  return totalcost
end

local n, m = io.read("*n", "*n")
local edge = {}
for i = 1, n do
  local c = io.read("*n")
  edge[i] = {}
  edge[i].c, edge[i].i1, edge[i].i2 = c, i, n + 1
end
for i = 1, m do
  local a, b, r = io.read("*n", "*n", "*n")
  edge[n + i] = {}
  edge[n + i].c, edge[n + i].i1, edge[n + i].i2 = r, a, b
end
local ret = kruskal(n + 1, edge)
if 99999999999999 < ret then
  print("100000000000000")
else
  print(ret)
end


Score : 100 points

Problem Statement

As a New Year's gift, Dolphin received a string s of length 19.

The string s has the following format: [five lowercase English letters],[seven lowercase English letters],[five lowercase English letters].

Dolphin wants to convert the comma-separated string s into a space-separated string.

Write a program to perform the conversion for him.

Constraints

The length of s is 19.

The sixth and fourteenth characters in s are ,.

The other characters in s are lowercase English letters.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string after the conversion.

Sample Input 1

happy,newyear,enjoy

Sample Output 1

happy newyear enjoy

Replace all the commas in happy,newyear,enjoy with spaces to obtain happy newyear enjoy.

Sample Input 2

haiku,atcoder,tasks

Sample Output 2

haiku atcoder tasks

Sample Input 3

abcde,fghihgf,edcba

Sample Output 3

abcde fghihgf edcba


local sx,sy,tx,ty=io.read("n","n","n","n")
local dx=tx-sx
local dy=ty-sy
local path=string.rep("U",dy)..string.rep("R",dx)..
        string.rep("D",dy)..string.rep("L",dx)..
        "L"..string.rep("U",dy+1)..string.rep("R",dx+1).."D"..
        "R"..string.rep("D",dy+1)..string.rep("L",dx+1).."U"
print(path)

Score : 300 points

Problem Statement

Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.

Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.

Here, both the x- and y-coordinates before and after each movement must be integers.

He will first visit the point (tx,ty) where sx < tx and sy < ty, then go back to the point (sx,sy), then visit the point (tx,ty) again, and lastly go back to the point (sx,sy).

Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points (sx,sy) and (tx,ty).

Under this condition, find a shortest path for him.

Constraints

-1000 ≤ sx < tx ≤ 1000

-1000 ≤ sy < ty ≤ 1000

sx,sy,tx and ty are integers.

Input

The input is given from Standard Input in the following format:

sx sy tx ty

Output

Print a string S that represents a shortest path for Dolphin.

The i-th character in S should correspond to his i-th movement.

The directions of the movements should be indicated by the following characters:

U: Up

D: Down

L: Left

R: Right

If there exist multiple shortest paths under the condition, print any of them.

Sample Input 1

0 0 1 2

Sample Output 1

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

Going from (sx,sy) to (tx,ty) for the first time: (0,0) → (0,1) → (0,2) → (1,2)

Going from (tx,ty) to (sx,sy) for the first time: (1,2) → (1,1) → (1,0) → (0,0)

Going from (sx,sy) to (tx,ty) for the second time: (0,0) → (-1,0) → (-1,1) → (-1,2) → (-1,3) → (0,3) → (1,3) → (1,2)

Going from (tx,ty) to (sx,sy) for the second time: (1,2) → (2,2) → (2,1) → (2,0) → (2,-1) → (1,-1) → (0,-1) → (0,0)

Sample Input 2

-2 -2 1 1

Sample Output 2

UURRURRDDDLLDLLULUUURRURRDDDLLDL


local a, b = io.read("*n", "*n")
local c, d = io.read("*n", "*n")
a = c - a
b = d - b
for i = 1, a do
  io.write("R")
end
for i = 1, b do
  io.write("U")
end
for i = 1, a do
  io.write("L")
end
for i = 1, b do
  io.write("D")
end
io.write("D")
for i = 1, a + 1 do
  io.write("R")
end
for i = 1, b + 1 do
  io.write("U")
end
io.write("LU")
for i = 1, a + 1 do
  io.write("L")
end
for i = 1, b + 1 do
  io.write("D")
end
print("R")


local sx, sy, tx, ty = io.read("n","n","n","n")
local t = {}
local function _p(a) table.insert(t, a) end
local function pp(a,c) for i=1,c do _p(a) end end
tx = tx - sx
ty = ty - sy

local h_to = tx > 0 and "R" or "L"
local h_bk = tx > 0 and "L" or "R"
local v_to = ty > 0 and "U" or "D"
local v_bk = ty > 0 and "D" or "U"

pp(h_to, math.abs(tx))
pp(v_to, math.abs(ty))
pp(h_bk, math.abs(tx))
pp(v_bk, math.abs(ty))
pp(v_bk, 1)
pp(h_to, math.abs(tx))
pp(h_to, 1)
pp(v_to, 1)
pp(v_to, math.abs(ty))
pp(h_bk, 1)
pp(v_to, 1)
pp(h_bk, math.abs(tx))
pp(h_bk, 1)
pp(v_bk, math.abs(ty))
pp(v_bk, 1)
pp(h_to, 1)

print(table.concat(t,""))


local n, m = io.read("*n", "*n")
local edge = {}
local edgeidx = {}
for i = 1, n do
  edge[i] = {}
  edgeidx[i] = {}
end
local edgeuse = {}
for i = 1, m do
  edgeuse[i] = false
  local a, b, c = io.read("*n", "*n", "*n")
  edge[a][b] = c
  edgeidx[a][b] = i
  edge[b][a] = c
  edgeidx[b][a] = i
end
local inf = 1000000007
local len = {}
local asked = {}
local function getpos()
  local cand = 0
  for i = 1, n do
    if not asked[i] then
      if cand == 0 or len[i] < len[cand] then
        cand = i
      end
    end
  end
  return cand
end
local function solve(spos)
  for i = 1, n do
    asked[i] = false
    len[i] = i == spos and 0 or inf
  end
  for i = 1, n do
    local src = getpos()
    asked[src] = true
    for dst, cost in pairs(edge[src]) do
      if len[dst] + cost == len[src] then
        edgeuse[edgeidx[dst][src]] = true
      end
      if len[src] + cost < len[dst] then
        len[dst] = len[src] + cost
      end
    end
  end
end

for i = 1, n do
  solve(i)
end

local ret = 0
for i = 1, m do
  if not edgeuse[i] then ret = ret + 1 end
end
print(ret)

Score : 400 points

Problem Statement

You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.

The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

A connected graph is a graph where there is a path between every pair of different vertices.

Find the number of the edges that are not contained in any shortest path between any pair of different vertices.

Constraints

2≤N≤100

N-1≤M≤min(N(N-1)/2,1000)

1≤a_i,b_i≤N

1≤c_i≤1000

c_i is an integer.

The given graph contains neither self-loops nor double edges.

The given graph is connected.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.

Sample Input 1

3 3
1 2 1
1 3 1
2 3 3

Sample Output 1

1

In the given graph, the shortest paths between all pairs of different vertices are as follows:

The shortest path from vertex 1 to vertex 2 is: vertex 1 → vertex 2, with the length of 1.

The shortest path from vertex 1 to vertex 3 is: vertex 1 → vertex 3, with the length of 1.

The shortest path from vertex 2 to vertex 1 is: vertex 2 → vertex 1, with the length of 1.

The shortest path from vertex 2 to vertex 3 is: vertex 2 → vertex 1 → vertex 3, with the length of 2.

The shortest path from vertex 3 to vertex 1 is: vertex 3 → vertex 1, with the length of 1.

The shortest path from vertex 3 to vertex 2 is: vertex 3 → vertex 1 → vertex 2, with the length of 2.

Thus, the only edge that is not contained in any shortest path, is the edge of length 3 connecting vertex 2 and vertex 3, hence the output should be 1.

Sample Input 2

3 2
1 2 1
2 3 1

Sample Output 2

0

Every edge is contained in some shortest path between some pair of different vertices.


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

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

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

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

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

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

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

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

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

-- dijkstra's algorithm
local function find_shortest_path_all(adj_list, src)
    local from1 = {}
    from1[src] = 0
    local prevs = {}
    local q = Heap.new(function (v1, v2)
        return v1[2] < v2[2]
    end)
    local proved = {}
    q:insertq({src, 0, {}})
    while q:count() > 0 do
        local elem = q:remove_top()
        local cur_v, cur_cost, path = table.unpack(elem)
        if not proved[cur_v] then
            proved[cur_v] = true
            --[[
            if cur_v == dst then
                return cur_cost
            end
            ]]
            path = {table.unpack(path), cur_v}
            for _, link in ipairs(adj_list[cur_v]) do
                local to, cost = table.unpack(link)
                if not proved[to] then
                    -- compare costs
                    local before = from1[to]
                    local candidate = cur_cost + cost
                    if not before or candidate < before then
                        from1[to] = candidate
                        prevs[to] = cur_v
                        q:insertq({to, candidate, path})
                    end
                end
            end
        end
    end
    return from1, prevs
end

local function make_path(prevs, src, dst)
    local path = {}
    path[#path+1] = dst
    local cur = dst
    while cur ~= src do
        local next = prevs[cur]
        path[#path+1] = next
        cur = next
    end
    -- reverse
    for i=1, #path//2 do
        path[i], path[#path-i+1] = path[#path-i+1], path[i]
    end
    return path
end

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

local edges = {}
for i=1,M do
    local a, b, cost = io.read("n", "n", "n")
    edges[#edges+1] = {a, b, cost}
end

local adj_list = {}
for i=1,N do
    adj_list[i] = {}
end

local edge_check = {}
for s=1,N do
    edge_check[s] = {}
end

for i=1,M do
    local a, b, cost = table.unpack(edges[i])
    local list = adj_list[a]
    list[#list+1] = {b, cost}
    local list2 = adj_list[b]
    list2[#list2+1] = {a, cost}
    local small = math.min(a, b)
    local big = math.max(a, b)
    edge_check[small][big] = 0
end

for s=1,N do
    local c, prevs = find_shortest_path_all(adj_list, s)
    for dd=1,N do
        if dd ~= s then
            local ss = prevs[dd]
            local small = math.min(ss, dd)
            local big = math.max(ss, dd)
            edge_check[small][big] = edge_check[small][big] + 1
        end
    end
end

local ans = 0
for s=1,N do
    for d=s+1,N do
        local count = edge_check[s][d]
        if count then
            --print(s,d,count)
            if count == 0 then
                ans = ans + 1
            end
        end
    end
end
print(ans)


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

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

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

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

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

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

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

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

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

-- dijkstra's algorithm
local function find_shortest_path_all(adj_list, src)
    local from1 = {}
    local prevs = {}
    local q = Heap.new(function (v1, v2)
        return v1[2] < v2[2]
    end)
    local proved = {}
    q:insertq({src, 0, {}})
    while q:count() > 0 do
        local elem = q:remove_top()
        local cur_v, cur_cost, path = table.unpack(elem)
        if not proved[cur_v] then
            proved[cur_v] = true
            --[[
            if cur_v == dst then
                return cur_cost
            end
            ]]
            path = {table.unpack(path), cur_v}
            for _, link in ipairs(adj_list[cur_v]) do
                local to, cost = table.unpack(link)
                if not proved[to] then
                    -- compare costs
                    local before = from1[to]
                    local candidate = cur_cost + cost
                    if not before or candidate < before then
                        from1[to] = candidate
                        prevs[to] = cur_v
                        q:insertq({to, candidate, path})
                    end
                end
            end
        end
    end
    return from1, prevs
end

local function make_path(prevs, src, dst)
    local path = {}
    path[#path+1] = dst
    local cur = dst
    while cur ~= src do
        local next = prevs[cur]
        path[#path+1] = next
        cur = next
    end
    -- reverse
    for i=1, #path//2 do
        path[i], path[#path-i+1] = path[#path-i+1], path[i]
    end
    return path
end

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

local edges = {}
for i=1,M do
    local a, b, cost = io.read("n", "n", "n")
    edges[#edges+1] = {a, b, cost}
end

local adj_list = {}
for i=1,N do
    adj_list[i] = {}
end

local edge_check = {}
for s=1,N do
    edge_check[s] = {}
end

for i=1,M do
    local a, b, cost = table.unpack(edges[i])
    local list = adj_list[a]
    list[#list+1] = {b, cost}
    local list2 = adj_list[b]
    list2[#list2+1] = {a, cost}
    local small = math.min(a, b)
    local big = math.max(a, b)
    edge_check[small][big] = 0
end

for s=1,N do
    local c, prevs = find_shortest_path_all(adj_list, s)
    for dd=1,N do
        if dd ~= s then
            local ss = prevs[dd]
            local small = math.min(ss, dd)
            local big = math.max(ss, dd)
            edge_check[small][big] = edge_check[small][big] + 1
        end
    end
end

local ans = 0
for s=1,N do
    for d=s+1,N do
        local count = edge_check[s][d]
        if count then
            --print(s,d,count)
            if count == 0 then
                ans = ans + 1
            end
        end
    end
end
print(ans)


Score : 300 points

Problem Statement

Snuke has a calculator. It has a display and two buttons.

Initially, the display shows an integer x.
Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:

Button A: When pressed, the value on the display is incremented by 1.

Button B: When pressed, the sign of the value on the display is reversed.

Find the minimum number of times Snuke needs to press the buttons to achieve his objective.
It can be shown that the objective is always achievable regardless of the values of the integers x and y.

Constraints

x and y are integers.

|x|, |y| ≤ 10^9

x and y are different.

Input

The input is given from Standard Input in the following format:

x y

Output

Print the minimum number of times Snuke needs to press the buttons to achieve his objective.

Sample Input 1

10 20

Sample Output 1

10

Press button A ten times.

Sample Input 2

10 -10

Sample Output 2

1

Press button B once.

Sample Input 3

-10 -20

Sample Output 3

12

Press the buttons as follows:

Press button B once.

Press button A ten times.

Press button B once.


local x,y=io.read("*n","*n")
if x>=0 and y>=0 then
    print(math.abs(x-y))
elseif x>=0 and 0>y then
    print(math.abs(x+y)+1)
elseif 0>x and 0>y then
    print(math.abs(x-y)+2)
end


local x, y = io.read("*n", "*n")
if 0 <= x and 0 <= y then
  if x <= y then
    print(y - x)
  else
    print(2 + x - y)
  end
elseif x < 0 and 0 <= y then
  print(1 + math.abs(x + y))
elseif x < 0 and y < 0 then
  if x <= y then
    print(y - x)
  else
    print(2 + x - y)
  end
else
  print(1 + math.abs(x + y))
end


Score : 600 points

Problem Statement

A tetromino is a figure formed by joining four squares edge to edge.
We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively:

Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession are a_I, a_O, a_T, a_J, a_L, a_S and a_Z, respectively.
Snuke will join K of his tetrominos to form a rectangle that is two squares tall and 2K squares wide.
Here, the following rules must be followed:

When placing each tetromino, rotation is allowed, but reflection is not.

Each square in the rectangle must be covered by exactly one tetromino.

No part of each tetromino may be outside the rectangle.

Snuke wants to form as large a rectangle as possible.
Find the maximum possible value of K.

Constraints

0≤a_I,a_O,a_T,a_J,a_L,a_S,a_Z≤10^9

a_I+a_O+a_T+a_J+a_L+a_S+a_Z≥1

Input

The input is given from Standard Input in the following format:

a_I a_O a_T a_J a_L a_S a_Z

Output

Print the maximum possible value of K. If no rectangle can be formed, print 0.

Sample Input 1

2 1 1 0 0 0 0

Sample Output 1

3

One possible way to form the largest rectangle is shown in the following figure:

Sample Input 2

0 0 10 0 0 0 0

Sample Output 2

0

No rectangle can be formed.


Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

The input is given from Standard Input in the following format:

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


s = io.read()
a, op, b = s:match("(%d+) (%+) (%d+)")
if a then
  print(tonumber(a) + tonumber(b))
else
  a, op, b = s:match("(%d+) (%-) (%d+)")
  print(tonumber(a) - tonumber(b))
end


local n=io.read("*n")
local a_map={}
for i=(n%2==0 and 1 or 0),n,2 do
    a_map[i]=(i==0 and 1 or 2)
end

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

local counter=1
for k,v in pairs(a) do
    local checker=(a[k] and a_map[k] and a[k]==a_map[k])
    counter=(checker and counter*v%1000000007 or 0)
end
print(counter)

Score : 300 points

Problem Statement

There are N people, conveniently numbered 1 through N.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person i is A_i.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo 10^9+7.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print 0.

Constraints

1≦N≦10^5

0≦A_i≦N-1

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the number of the possible orders in which they were standing, modulo 10^9+7.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

2,1,4,5,3

2,5,4,1,3

3,1,4,5,2

3,5,4,1,2

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is 0.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


local n=io.read("*n")
local a_map={}
for i=(n%2==0 and 1 or 0),n,2 do
    a_map[i]=(i==0 and 1 or 2)
end

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

if #a~=#a_map then
    print(0)
    return
end

local counter=1
for k,v in pairs(a_map) do
    counter=(a[k]==a_map[k] and counter*v%1000000007 or 0)
end
print(counter)


c = io.read()
if string.find(c , "a" or "i" or "u" or "e" or "o") == nil then
	print("consonant")
else
	print("vowel")
end

Score : 100 points

Problem Statement

Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: a, e, i, o and u.

Constraints

c is a lowercase English letter.

Input

The input is given from Standard Input in the following format:

c

Output

If c is a vowel, print vowel. Otherwise, print consonant.

Sample Input 1

a

Sample Output 1

vowel

Since a is a vowel, print vowel.

Sample Input 2

z

Sample Output 2

consonant

Sample Input 3

s

Sample Output 3

consonant


c = io.read()
if(c == "a" or c == "e" or c == "i" or c == "o" or c == "u") then print("vowel") else print("consonant") end


h,w=io.read("*n","*n","*l")
c={}
for i=1,h do
    c[i]=io.read()
end
for i=1,2*h do
    print(c[(i+1)//2])
end


h,w=io.read("*n","*n","*l")
c={}
for i=1,h do
    c[i]={}
    for j=1,w do
        c[i][j]=io.read()
    end
end
for i=1,2*h do
    for j=1,w do
        print(c[(i+1)//2][j])
    end
end


local n, k, l = io.read("*n", "*n", "*n")

local function uf_initialize(n)
  local parent = {}
  for i = 1, n do parent[i] = i end
  return parent
end

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

local p1 = uf_initialize(n)
for i = 1, k do
  local p, q = io.read("*n", "*n")
  local pr, qr = uf_findroot(p, p1), uf_findroot(q, p1)
  p1[qr], p1[q] = pr, pr
end

local p2 = uf_initialize(n)
for i = 1, l do
  local r, s = io.read("*n", "*n")
  local rr, sr = uf_findroot(r, p2), uf_findroot(s, p2)
  p2[sr], p2[s] = rr, rr
end

local group = {}
for i = 1, n do
  local r1, r2 = uf_findroot(i, p1), uf_findroot(i, p2)
  if not group[r1] then group[r1] = {} end
  if not group[r1][r2] then
    group[r1][r2] = 1
  else
    group[r1][r2] = group[r1][r2] + 1
  end
end
for i = 1, n do
  local r1, r2 = uf_findroot(i, p1), uf_findroot(i, p2)
  io.write(group[r1][r2])
  io.write(i == n and "\n" or " ")
end

Score : 400 points

Problem Statement

There are N cities. There are also K roads and L railways, extending between the cities.
The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities.
No two roads connect the same pair of cities. Similarly, no two railways connect the same pair of cities.

We will say city A and B are connected by roads if city B is reachable from city A by traversing some number of roads. Here, any city is considered to be connected to itself by roads.
We will also define connectivity by railways similarly.

For each city, find the number of the cities connected to that city by both roads and railways.

Constraints

2 ≦ N ≦ 2*10^5

1 ≦ K, L≦ 10^5

1 ≦ p_i, q_i, r_i, s_i ≦ N

p_i < q_i

r_i < s_i

When i ≠ j, (p_i, q_i) ≠ (p_j, q_j)

When i ≠ j, (r_i, s_i) ≠ (r_j, s_j)

Input

The input is given from Standard Input in the following format:

N K L
p_1 q_1
:
p_K q_K
r_1 s_1
:
r_L s_L

Output

Print N integers. The i-th of them should represent the number of the cities connected to the i-th city by both roads and railways.

Sample Input 1

4 3 1
1 2
2 3
3 4
2 3

Sample Output 1

1 2 2 1

All the four cities are connected to each other by roads.

By railways, only the second and third cities are connected. Thus, the answers for the cities are 1, 2, 2 and 1, respectively.

Sample Input 2

4 2 2
1 2
2 3
1 4
2 3

Sample Output 2

1 2 2 1

Sample Input 3

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

Sample Output 3

1 1 2 1 2 2 2


Score : 100 points

Problem Statement

Snuke is going to open a contest named "AtCoder s Contest".
Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.

Snuke has decided to abbreviate the name of the contest as "AxC".
Here, x is the uppercase English letter at the beginning of s.

Given the name of the contest, print the abbreviation of the name.

Constraints

The length of s is between 1 and 100, inclusive.

The first character in s is an uppercase English letter.

The second and subsequent characters in s are lowercase English letters.

Input

The input is given from Standard Input in the following format:

AtCoder s Contest

Output

Print the abbreviation of the name of the contest.

Sample Input 1

AtCoder Beginner Contest

Sample Output 1

ABC

The contest in which you are participating now.

Sample Input 2

AtCoder Snuke Contest

Sample Output 2

ASC

This contest does not actually exist.

Sample Input 3

AtCoder X Contest

Sample Output 3

AXC


Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

The input is given from Standard Input in the following format:

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


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

local counter=0
for i=1,n do
    local sum=a[i]+a[i+1]
    if sum>x then
        local diff=sum-x
        counter=counter+diff
        if diff<a[i+1] then
            a[i+1]=a[i+1]-diff
        else
            diff=diff-a[i+1]
            a[i+1]=0
            a[i]=a[i]-diff
        end
    end
end
print(counter)

Score : 300 points

Problem Statement

There are N boxes arranged in a row.
Initially, the i-th box from the left contains a_i candies.

Snuke can perform the following operation any number of times:

Choose a box containing at least one candy, and eat one of the candies in the chosen box.

His objective is as follows:

Any two neighboring boxes contain at most x candies in total.

Find the minimum number of operations required to achieve the objective.

Constraints

2 ≤ N ≤ 10^5

0 ≤ a_i ≤ 10^9

0 ≤ x ≤ 10^9

Input

The input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the minimum number of operations required to achieve the objective.

Sample Input 1

3 3
2 2 2

Sample Output 1

1

Eat one candy in the second box.
Then, the number of candies in each box becomes (2, 1, 2).

Sample Input 2

6 1
1 6 1 2 0 4

Sample Output 2

11

For example, eat six candies in the second box, two in the fourth box, and three in the sixth box.
Then, the number of candies in each box becomes (1, 0, 1, 0, 0, 1).

Sample Input 3

5 9
3 1 4 1 5

Sample Output 3

0

The objective is already achieved without performing operations.

Sample Input 4

2 0
5 5

Sample Output 4

10

All the candies need to be eaten.


local n, x = io.read("*n", "*n", "*l")
local str = io.read()
local a = {}
for v in str:gmatch("%d+") do
  table.insert(a, tonumber(v))
end
local cnt = 0
for i = 1, n - 1 do
  local rem = a[i] + a[i + 1] - x
  if 0 < rem then
    cnt = cnt + rem
    if rem <= a[i + 1] then
      a[i + 1] = a[i + 1] - rem
    else
      a[i + 1] = 0
      a[i] = a[i] - (rem - a[i + 1])
    end
  end
end
print(cnt)


local function solve(a)
  local cnt = 0
  while 2 < a do
    a = (a - 1) // 2
    cnt = cnt + 1
  end
  return cnt
end

local x = io.read("*n")
local a = 2

local min, max = 2, 100000000000000000
while 1 < max - min do
  local mid = (min + max) // 2
  if solve(mid) <= x then
    min = mid
  else
    max = mid
  end
end
print(max - 1)

Score : 100 points

Problem Statement

We have a cord whose length is a positive integer. We will perform the following condition until the length of the cord becomes at most 2:

Operation:
Cut the rope at two positions to obtain three cords, each with a length of a positive integer.
Among these, discard one with the longest length and one with the shortest length, and keep the remaining one.

Let f(N) be the maximum possible number of times to perform this operation, starting with a cord with the length N.

You are given a positive integer X. Find the maximum integer N such that f(N)=X.

Constraints

1 \leq X \leq 40

Input

The input is given from Standard Input in the following format:

X

Output

Print the value of the maximum integer N such that f(N)=X.

Sample Input 1

2

Sample Output 1

14


local x = io.read("*n")
local a = 2
for i = 1, x do a = a * 3 - 1 end
print(a)


l = io.read("*l")
t = {string.byte(l, 1, -1)}
i, ans = 1, 0

for j = 2, string.len(l) do
	if t[i] ~= t[j] then
		ans = ans + 1
	end
	i = i + 1
end
print(ans)

Score : 100 points

Problem Statement

Two students of AtCoder Kindergarten are fighting over candy packs.

There are three candy packs, each of which contains a, b, and c candies, respectively.

Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.

Note that Evi cannot take candies out of the packs, and the whole contents of each pack must be given to one of the students.

Constraints

1 ≦ a, b, c ≦ 100

Input

The input is given from Standard Input in the following format:

a b c

Output

If it is possible to distribute the packs so that each student gets the same number of candies, print Yes. Otherwise, print No.

Sample Input 1

10 30 20

Sample Output 1

Yes

Give the pack with 30 candies to one student, and give the two packs with 10 and 20 candies to the other. Then, each gets 30 candies.

Sample Input 2

30 30 100

Sample Output 2

No

In this case, the student who gets the pack with 100 candies always has more candies than the other.

Note that every pack must be given to one of them.

Sample Input 3

56 25 31

Sample Output 3

Yes


a, b, c = io.read("*n", "*n", "*n")
max = math.max(a, b, c)
rem = a + b + c - max

if rem == 0 then
	print("Yes")
else
	print("No")
end


local w,h,n=io.read("*n","*n","*n")
local rectangle={}
for i=1,h do
    rectangle[i]={}
    for j=1,w do
        rectangle[i][j]=1
    end
end
for i=1,n do
    local x,y,a=io.read("*n","*n","*n")
    if a==1 then
        for j=1,h do
            for k=1,x do
                rectangle[j][k]=0
            end
        end
    end
    if a==2 then
        for j=1,h do
            for k=x+1,w do
                rectangle[j][k]=0
            end
        end
    end
    if a==3 then
        for j=1,y do
            for k=1,w do
                rectangle[j][k]=0
            end
        end
    end
    if a==4 then
        for j=y+1,h do
            for k=1,w do
                rectangle[j][k]=0
            end
        end
    end
end

local total=0
for i=1,h do
    for j=1,w do
        total=total+rectangle[i][j]
    end
end
print(total)

Score : 200 points

Problem Statement

There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.

Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) point was (x_i, y_i).

Then, he created an integer sequence a of length N, and for each 1 ≦ i ≦ N, he painted some region within the rectangle black, as follows:

If a_i = 1, he painted the region satisfying x < x_i within the rectangle.

If a_i = 2, he painted the region satisfying x > x_i within the rectangle.

If a_i = 3, he painted the region satisfying y < y_i within the rectangle.

If a_i = 4, he painted the region satisfying y > y_i within the rectangle.

Find the area of the white region within the rectangle after he finished painting.

Constraints

1 ≦ W, H ≦ 100

1 ≦ N ≦ 100

0 ≦ x_i ≦ W (1 ≦ i ≦ N)

0 ≦ y_i ≦ H (1 ≦ i ≦ N)

W, H (21:32, added), x_i and y_i are integers.

a_i (1 ≦ i ≦ N) is 1, 2, 3 or 4.

Input

The input is given from Standard Input in the following format:

W H N
x_1 y_1 a_1
x_2 y_2 a_2
:
x_N y_N a_N

Output

Print the area of the white region within the rectangle after Snuke finished painting.

Sample Input 1

5 4 2
2 1 1
3 3 4

Sample Output 1

9

The figure below shows the rectangle before Snuke starts painting.

First, as (x_1, y_1) = (2, 1) and a_1 = 1, he paints the region satisfying x < 2 within the rectangle:

Then, as (x_2, y_2) = (3, 3) and a_2 = 4, he paints the region satisfying y > 3 within the rectangle:

Now, the area of the white region within the rectangle is 9.

Sample Input 2

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

Sample Output 2

0

It is possible that the whole region within the rectangle is painted black.

Sample Input 3

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

Sample Output 3

64


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

local common=0
for i=1,n do
    if s:sub(#s-i+1,#s)==t:sub(1,i) then
        common=math.max(common,#t:sub(1,i))
    end
end
print(n+n-common)

Score : 200 points

Problem Statement

Snuke is interested in strings that satisfy the following conditions:

The length of the string is at least N.

The first N characters equal to the string s.

The last N characters equal to the string t.

Find the length of the shortest string that satisfies the conditions.

Constraints

1≤N≤100

The lengths of s and t are both N.

s and t consist of lowercase English letters.

Input

The input is given from Standard Input in the following format:

N
s
t

Output

Print the length of the shortest string that satisfies the conditions.

Sample Input 1

3
abc
cde

Sample Output 1

5

The shortest string is abcde.

Sample Input 2

1
a
z

Sample Output 2

2

The shortest string is az.

Sample Input 3

4
expr
expr

Sample Output 3

4

The shortest string is expr.


local n, x = io.read("*n", "*n")
if x == 1 or x == 2 * n - 1 then
  print("No")
elseif n == 2 then
  print("Yes\n1\n2\n3")
else
  print("Yes")
  if x == 2 then
    for i = 1, n - 3 do
      print(i + 4)
    end
    print("4\n1\n2\n3")
    for i = n + 2, 2 * n - 1 do
      print(i)
    end
  else
    for i = 1, n - 2 do
      if i <= x - 3 then
        print(i)
      else
        print(i + 4)
      end
    end
    print(x - 1 .. "\n" .. x .. "\n" .. x + 1 .. "\n" .. x - 2)
    for i = n - 1, 2 * n - 5 do
      if i <= x - 3 then
        print(i)
      else
        print(i + 4)
      end
    end
  end
end

Score : 400 points

Problem Statement

We have a pyramid with N steps, built with blocks.
The steps are numbered 1 through N from top to bottom.
For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally.
The pyramid is built so that the blocks at the centers of the steps are aligned vertically.

A pyramid with N=4 steps

Snuke wrote a permutation of (1, 2, ..., 2N-1) into the blocks of step N.
Then, he wrote integers into all remaining blocks, under the following rule:

The integer written into a block b must be equal to the median of the three integers written into the three blocks directly under b, or to the lower left or lower right of b.

Writing integers into the blocks

Afterwards, he erased all integers written into the blocks.
Now, he only remembers that the integer written into the block of step 1 was x.

Construct a permutation of (1, 2, ..., 2N-1) that could have been written into the blocks of step N, or declare that Snuke's memory is incorrect and such a permutation does not exist.

Constraints

2≤N≤10^5

1≤x≤2N-1

Input

The input is given from Standard Input in the following format:

N x

Output

If no permutation of (1, 2, ..., 2N-1) could have been written into the blocks of step N, print No.

Otherwise, print Yes in the first line, then print 2N-1 lines in addition.

The i-th of these 2N-1 lines should contain the i-th element of a possible permutation.

Sample Input 1

4 4

Sample Output 1

Yes
1
6
3
7
4
5
2

This case corresponds to the figure in the problem statement.

Sample Input 2

2 1

Sample Output 2

No

No matter what permutation was written into the blocks of step N, the integer written into the block of step 1 would be 2.


local mma = math.max
local mfl, mce, mmi = math.floor, math.ceil, math.min

local AvlTree = {}
AvlTree.makenode = function(self, val, parent)
  local i = self.box[#self.box]
  if not i then i = #self.v + 1
  else table.remove(self.box)
  end
  self.v[i], self.p[i] = val, parent
  self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  return i
end
AvlTree.create = function(self, lessthan, n)
  self.lessthan = lessthan
  self.root = 1
  self.box = {}
  for i = n + 1, 2, -1 do table.insert(self.box, i) end
  -- value, leftCount, rightCount, left, right, parent
  self.v, self.lc, self.rc, self.l, self.r, self.p = {}, {}, {}, {}, {}, {}
  for i = 1, n + 1 do
    self.v[i], self.p[i] = 0, 1
    self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  end
end

AvlTree.recalc = function(self, i)
  local kl, kr = self.l[i], self.r[i]
  if 1 < kl then self.lc[i] = 1 + mma(self.lc[kl], self.rc[kl])
  else self.lc[i] = 0
  end
  if 1 < kr then self.rc[i] = 1 + mma(self.lc[kr], self.rc[kr])
  else self.rc[i] = 0
  end
end
AvlTree.recalcAll = function(self, i)
  while 1 < i do
    self:recalc(i)
    i = self.p[i]
  end
end

AvlTree.rotR = function(self, parent)
  local granp, child = self.p[parent], self.l[parent]
  self.r[child], self.l[parent] = parent, self.r[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.l[parent]] = parent
  if 1 < granp then
    if self.l[granp] == parent then
      self.l[granp] = child
    else
      self.r[granp] = child
    end
  else
    self.root = child
  end
end

AvlTree.rotL = function(self, parent)
  local granp, child = self.p[parent], self.r[parent]
  self.l[child], self.r[parent] = parent, self.l[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.r[parent]] = parent
  if 1 < granp then
    if self.r[granp] == parent then
      self.r[granp] = child
    else
      self.l[granp] = child
    end
  else
    self.root = child
  end
end

AvlTree.rotLR = function(self, lparent, rparent)
  local sp, sl, sr = self.p, self.l, self.r
  local granp, d = sp[rparent], sr[lparent]
  sp[lparent], sr[lparent] = d, sl[d]
  sp[rparent], sl[rparent] = d, sr[d]
  sp[sl[d]], sp[sr[d]] = lparent, rparent
  sp[d], sl[d], sr[d] = granp, lparent, rparent
  if 1 < granp then
    if sr[granp] == rparent then sr[granp] = d
    else sl[granp] = d
    end
  else self.root = d
  end
end

AvlTree.rotRL = function(self, rparent, lparent)
  local sp, sl, sr = self.p, self.l, self.r
  local granp, d = sp[lparent], sl[rparent]
  sp[rparent], sl[rparent] = d, sr[d]
  sp[lparent], sr[lparent] = d, sl[d]
  sp[sr[d]], sp[sl[d]] = rparent, lparent
  sp[d], sr[d], sl[d] = granp, rparent, lparent
  if 1 < granp then
    if sl[granp] == lparent then sl[granp] = d
    else sr[granp] = d
    end
  else self.root = d
  end
end

AvlTree.empty = function(self) return self.root <= 1 end

AvlTree.push = function(self, val)
  if self.root <= 1 then self.root = self:makenode(val, 1) return end
  local pos = self.root
  while true do
    if self.lessthan(val, self.v[pos]) then
      if 1 < self.l[pos] then
        pos = self.l[pos]
      else
        self.l[pos] = self:makenode(val, pos)
        pos = self.l[pos]
        break
      end
    else
      if 1 < self.r[pos] then
        pos = self.r[pos]
      else
        self.r[pos] = self:makenode(val, pos)
        pos = self.r[pos]
        break
      end
    end
  end
  while 1 < pos do
    local child, parent = pos, self.p[pos]
    if parent <= 1 then
      break
    end
    self:recalc(parent)
    local lcp_m_rcp = self.lc[parent] - self.rc[parent]
    if lcp_m_rcp % 2 ~= 0 then -- 1 or -1
      pos = parent
    elseif lcp_m_rcp == 2 then
      if self.lc[child] - 1 == self.rc[child] then
        self:rotR(parent)
        self:recalcAll(parent)
      else
        self:rotLR(child, parent)
        self:recalc(child)
        self:recalcAll(parent)
      end
      break
    elseif lcp_m_rcp == -2 then
      if self.rc[child] - 1 == self.lc[child] then
        self:rotL(parent)
        self:recalcAll(parent)
      else
        self:rotRL(child, parent)
        self:recalc(child)
        self:recalcAll(parent)
      end
      break
    else
      break
    end
  end
end

AvlTree.rmsub = function(self, node)
  while 1 < node do
    self:recalc(node)
    if self.lc[node] == self.rc[node] then
      node = self.p[node]
    elseif self.lc[node] + 1 == self.rc[node] then
      self:recalcAll(self.p[node])
      break
    else
      if self.lc[self.r[node]] == self.rc[self.r[node]] then
        self:rotL(node)
        self:recalcAll(node)
        break
      elseif self.lc[self.r[node]] + 1 == self.rc[self.r[node]] then
        local nr = self.r[node]
        self:rotL(node)
        self:recalc(node)
        node = nr
      else
        local nr = self.r[node]
        local nrl = self.l[nr]
        self:rotRL(nr, node)
        self:recalc(nr)
        self:recalc(node)
        node = nrl
      end
    end
  end
end

AvlTree.pop = function(self)
  local node = self.root
  while 1 < self.l[node] do
    node = self.l[node]
  end
  local v = self.v[node]
  local kp = self.p[node]
  self.p[self.r[node]] = kp
  if 1 < kp then
    self.l[kp] = self.r[node]
    self:rmsub(kp)
  else
    self.root = self.r[node]
  end
  table.insert(self.box, node)
  return v
end

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

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

local function lt(p, q)
  return a[p] > a[q]
end
local avl = AvlTree.new(lt, m)
for i = 1, m do avl:push(i) end
while true do
  local top = avl:pop()
  if avl:empty() then
    print(a[top] - 1)
    break
  else
    local nxt = avl:pop()
    a[top] = a[top] - 1
    a[nxt] = a[nxt] - 1
    if 0 < a[nxt] then
      avl:push(nxt)
      avl:push(top)
    elseif 0 < a[top] then
      avl:push(top)
    end
    if avl:empty() then print(0) break end
  end
end

Score : 200 points

Problem Statement

There are K pieces of cakes.
Mr. Takahashi would like to eat one cake per day, taking K days to eat them all.

There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i.

Eating the same type of cake two days in a row would be no fun,
so Mr. Takahashi would like to decide the order for eating cakes that minimizes the number of days on which he has to eat the same type of cake as the day before.

Compute the minimum number of days on which the same type of cake as the previous day will be eaten.

Constraints

1 ≤ K ≤ 10000

1 ≤ T ≤ 100

1 ≤ a_i ≤ 100

a_1 + a_2 + ... + a_T = K

Input

The input is given from Standard Input in the following format:

K T
a_1 a_2 ... a_T

Output

Print the minimum number of days on which the same type of cake as the previous day will be eaten.

Sample Input 1

7 3
3 2 2

Sample Output 1

0

For example, if Mr. Takahashi eats cakes in the order of 2, 1, 2, 3, 1, 3, 1, he can avoid eating the same type of cake as the previous day.

Sample Input 2

6 3
1 4 1

Sample Output 2

1

There are 6 cakes.
For example, if Mr. Takahashi eats cakes in the order of 2, 3, 2, 2, 1, 2, he has to eat the same type of cake (i.e., type 2) as the previous day only on the fourth day.
Since this is the minimum number, the answer is 1.

Sample Input 3

100 1
100

Sample Output 3

99

Since Mr. Takahashi has only one type of cake, he has no choice but to eat the same type of cake as the previous day from the second day and after.


local k, n = io.read("*n", "*n")
local t = {}
for i = 1, n do
  local tmp = {}
  tmp.cnt = io.read("*n")
  tmp.idx = i
  t[i] = tmp
end
table.sort(t, function(a, b) return a.cnt < b.cnt end)
local vanish = 0
local lastate = 0
while vanish < n - 1 do
  local tgt = n
  if lastate == t[n].idx then
    tgt = n - 1
  end
  t[tgt].cnt = t[tgt].cnt - 1
  if t[tgt].cnt == 0 then vanish = vanish + 1 end
  table.sort(t, function(a, b) return a.cnt < b.cnt end)
  lastate = t[tgt].idx
end
print(t[n].cnt - 1)


a, b, c = io.read("*n", "*n", "*n")
if a ~= b and b ~= c and c ~= a then
	print(3)
elseif a == b and b == c and c == a then
	print(1)
else
	print(2)
end

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

The input is given from Standard Input in the following format:

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


local t = {}
for i = 1, 3 do
	t[io.read("*n")] = true
end
local ans = 0
for i = 1, 100 do
  if t[i] then
    ans = ans + 1
  end
end
print(ans)


t = {}
for i = 1, 3 do t[io.read("*n")] = true end
c = 0
for k, v in pairs(t) do c = c + 1 end
print(c)


local n = io.read()

local function getABC(str)
	local result
	for i=#str, 2, -1 do
		local a = string.sub(str, i, i)
		if a == "T" then
			local b = string.sub(str, i-1, i-1)
			if b == "S" then
				result = #str - i
				break
			end
		end
	end

	if not result then
		result = #str
	end
	if result % 2 ~= 0 then
		result = result + 1
	end
	return result
end

local r = getABC(n)
print(r)

Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

The input is given from Standard Input in the following format:

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


local str = io.read("*l")

local len = string.len(str)

local snum = 0
local tnum = 0
for i = 1,len do
	local j = string.sub(str,i,i)
	if j == "S" then
		snum = snum + 1
	elseif j == "T" then
		if snum > 0 then
			snum = snum - 1
		else
			tnum = tnum + 1
		end
	end
end
local ret = snum + tnum
print(ret)


local X = io.read()

local function main(str)
	local sPos = string.find(str, "ST")
	if sPos then
		str = string.sub(str, 2, string.len(str))
		return main(str)
	end
	print(string.len(str))
end

main(X)


local mfl, mce = math.floor, math.ceil
local mmi, mma = math.min, math.max
local pow2 = {1}
for i = 2, 26 do
  pow2[i] = 2 * pow2[i - 1]
end
local function bls(a, b)
  return a * pow2[b + 1]
end
local function brs(a, b)
  return a // pow2[b + 1]
end

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

local n = io.read("*n")
local st = SegTree.new(n, mma, -n-1)
local invpos = {}
for i = 1, n do invpos[i] = i end
for i = 1, n do
  local z = io.read("*n")
  st:setValue(i, -z, true)
  invpos[z] = i
end
st:updateAll()
local ret = 0
for i = 1, n do
  local pos = invpos[i]
  local rb = st:right_bound(-i + 1, pos, n)
  local lb = st:left_bound(-i + 1, 1, pos)
  ret = ret + i * (rb - pos) * (pos - lb)
end
print(ret)

Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the answer.

Note that the answer may not fit into a 32-bit integer.

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85


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

counter=0
for i=1,n do
    if a[a[i]]==i then
        counter=counter+1
    end
end
print(counter//2)

Score : 200 points

Problem Statement

There are N rabbits, numbered 1 through N.

The i-th (1≤i≤N) rabbit likes rabbit a_i.
Note that no rabbit can like itself, that is, a_i≠i.

For a pair of rabbits i and j (i＜j), we call the pair (i，j) a friendly pair if the following condition is met.

Rabbit i likes rabbit j and rabbit j likes rabbit i.

Calculate the number of the friendly pairs.

Constraints

2≤N≤10^5

1≤a_i≤N

a_i≠i

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the number of the friendly pairs.

Sample Input 1

4
2 1 4 3

Sample Output 1

2

There are two friendly pairs: (1，2) and (3，4).

Sample Input 2

3
2 3 1

Sample Output 2

0

There are no friendly pairs.

Sample Input 3

5
5 5 5 5 1

Sample Output 3

1

There is one friendly pair: (1，5).


local n = io.read("*n")
local a = {}
for i = 1, n do a[i] = io.read("*n") end
local cnt = 0
for i = 1, n - 1 do
  if(i < a[i] and a[a[i]] == i) then
    cnt = cnt + 1
  end
end
print(cnt)


local s=io.read()
local sable={}
for i=1,#s do
    sable[i]=s:byte(i)-97
end
local k=io.read("n")
for i=1,#s do
    local a=sable[i]
    if i~=#s and k>=26-a and a>0 then
        sable[i]=string.char(97)
        k=k-(26-a)
    elseif i==#s then
        sable[i]=string.char((sable[i]+k)%26+97)
    else
        sable[i]=string.char(sable[i]+97)
    end
end
print(table.concat(sable,""))

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


local s = io.read()
local k = io.read("*n")
local n = #s
local t = {}
local sch = string.char
for i = 1, n - 1 do
  local ti = s:sub(i, i):byte() - 97
  if 0 < ti then
    local cost = 26 - ti
    if cost <= k then
      k = k - cost
      ti = 0
    end
  end
  t[i] = sch(ti + 97)
end
local last = (s:sub(n, n):byte() - 97 + k) % 26
t[n] = sch(last + 97)
print(table.concat(t))


Score : 100 points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

The input is given from Standard Input in the following format:

a
b
h

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.


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


local S={}
S["a"]=io.read()
S["b"]=io.read()
S["c"]=io.read()

local discard="a"
while true do
    if #S[discard]==0 then
        print(discard:upper())
        break
    end
    discard=S[discard]:sub(1,1)
    S[discard]=S[discard]:sub(2)
end

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

The input is given from Standard Input in the following format:

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


local S={}
S["a"]=io.read()
S["b"]=io.read()
S["c"]=io.read()

local discard="a"
while true do
    discard=S[discard]:sub(1,1)
    S[discard]=S[discard]:sub(2,#S[discard])
    if S[discard]=="" then
        print(discard:upper())
        break
    end
end