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

local n, k = io.read("*n", "*n")
local sum, conv = {}, {}
sum[1] = {1, io.read("*n") - k}
for i = 2, n do
  sum[i] = {i, sum[i - 1][2] + io.read("*n") - k}
end
table.sort(sum, function(x, y) return x[2] < y[2] end)
local sumTypeCount = 1
local sumTypeList = {}
do
  conv[sum[1][2]] = 1
  sumTypeList[1] = sum[1][2]
  for i = 2, n do
    if sum[i][2] ~= sumTypeList[sumTypeCount] then
      sumTypeCount = sumTypeCount + 1
      conv[sum[i][2]] = sumTypeCount
      sumTypeList[sumTypeCount] = sum[i][2]
    end
  end
end
table.sort(sum, function(x, y) return x[1] < y[1] end)
local sumArrayForTree = {}
for i = 1, sumTypeCount do sumArrayForTree[i] = 0 end
for i = 1, n do
  sum[i] = sum[i][2]
  local idx = conv[sum[i]]
  sumArrayForTree[idx] = sumArrayForTree[idx] + 1
end

local segtree = SegTree.new(sumArrayForTree, function(a, b) return a + b end, 0)

local function lower_bound(ary, x)
  local num = #ary
  if num == 0 then return 1 end
  if(x <= ary[1]) then return 1 end
  if(ary[num] < x) then return num + 1 end
  local min, max = 1, num
  while(1 < max - min) do
    local mid = mfl((min + max) / 2)
    if(ary[mid] < x) then
      min = mid
    else
      max = mid
    end
  end
  return max
end

local bias = 0
local cnt = 0
for i = 1, n do
  local treeleft = i == 1 and lower_bound(sumTypeList, bias) or conv[bias]
  if treeleft <= sumTypeCount then
    cnt = cnt + segtree:getRange(treeleft, sumTypeCount)
  end
  segtree:decValue(conv[sum[i]])
  bias = sum[i]
end
print(cnt)


local x, y = io.read("n", "n")
local g1 = {1,3,5,7,8,10,12}
local g2 = {4,6,9,11}
local g3 = {2}
local function get(i)
    local groups = {g1,g2,g3}
    for k,v in ipairs(groups) do
        for kk,vv in ipairs(v) do
            if i == vv then
                return k
            end
        end
    end
    return -1
end
if get(x) == get(y) then print('Yes')
else print('No') end

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

Score : 100 points

Problem Statement

Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below.
Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.

Constraints

x and y are integers.

1 ≤ x < y ≤ 12

Input

Input is given from Standard Input in the following format:

x y

Output

If x and y belong to the same group, print Yes; otherwise, print No.

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No

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 DBG = true
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end
local function dbgpr_t(tbl, use_pairs)
    if DBG then
        local enum = ipairs
        if use_pairs then
            enum = pairs
        end
        dbgpr(tbl)
        io.write("[dbg]")
        for i,v in enum(tbl) do
            io.write(i)
            io.write(":")
            io.write(tostring(v))
            io.write(" ")
        end
        print("")
    end
end
local H, W = io.read("n", "n")
local INF = 99999999999
local function vert(H, W)
    local m = W % 3
    if m == 0 then
        return 0
    else
        return H
    end
end

local function horiz(H, W)
    return vert(W, H)
end

local function maxmindiff(a,b,c)
    local max = math.max(a,b,c)
    local min = math.min(a,b,c)
    return max - min
end

local function vh(H, W)
    local d = W // 3
    local h = H // 2
    local ans = INF
    for w=math.max(d,0),math.min(d+2,W) do
        local area1 = w * H
        local area2 = (W - w) * h
        local area3 = (W - w) * (H - h)
        ans = math.min(ans, maxmindiff(area1,area2,area3))
    end
    return ans
end

local function hv(H, W)
    return vh(W, H)
end

local answers = {vert(H, W), horiz(H, W), vh(H, W), hv(H, W)}
--dbgpr_t(answers)
print(math.min(table.unpack(answers)))

Score : 400 points

Problem Statement

There is a bar of chocolate with a height of H blocks and a width of W blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.

Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece.
Find the minimum possible value of S_{max} - S_{min}.

Constraints

2 ≤ H, W ≤ 10^5

Input

Input is given from Standard Input in the following format:

H W

Output

Print the minimum possible value of S_{max} - S_{min}.

Sample Input 1

3 5

Sample Output 1

0

In the division below, S_{max} - S_{min} = 5 - 5 = 0.

Sample Input 2

4 5

Sample Output 2

2

In the division below, S_{max} - S_{min} = 8 - 6 = 2.

Sample Input 3

5 5

Sample Output 3

4

In the division below, S_{max} - S_{min} = 10 - 6 = 4.

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000


local DBG = true
local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end
local function dbgpr_t(tbl, use_pairs)
    if DBG then
        local enum = ipairs
        if use_pairs then
            enum = pairs
        end
        dbgpr(tbl)
        io.write("[dbg]")
        for i,v in enum(tbl) do
            io.write(i)
            io.write(":")
            io.write(tostring(v))
            io.write(" ")
        end
        print("")
    end
end
local H, W = io.read("n", "n")
local INF = 99999999999
local function vert()
    local m = W % 3
    if m == 0 then
        return 0
    else
        return H
    end
end

local function horiz()
    local m = H % 3
    if m == 0 then
        return 0
    else
        return W
    end
end

local function maxmindiff(a,b,c)
    local max = math.max(a,b,c)
    local min = math.min(a,b,c)
    return max - min
end

local function vh()
    local d = W // 3
    local dd = H // 2
    local ans = INF
    for w=math.max(d-3,0),math.min(d+3,W) do
        local area1 = w * H
        for h=math.max(dd-3,0),math.min(dd+3,H) do
            local area2 = (W - w) * h
            local area3 = (W - w) * (H - h)
            ans = math.min(ans, maxmindiff(area1,area2,area3))
        end
    end
    return ans
end

local function hv()
    local d = H // 3
    local dd = W // 2
    local ans = INF
    for h=math.max(d-3,0),math.min(d+3,H) do
        local area1 = h * W
        for w=math.max(dd-3,0),math.min(dd+3,W) do
            local area2 = (H - h) * w
            local area3 = (H - h) * (W - w)
            ans = math.min(ans, maxmindiff(area1,area2,area3))
        end
    end
    return ans
end

local answers = {vert(), horiz(), vh(), hv()}
--dbgpr_t(answers)
print(math.min(table.unpack(answers)))


local PairingHeap={}

PairingHeap.meld=function(self,a,b)
    if not a then
        return b
    elseif not b then
        return a
    elseif a[1]<b[1] then
        b[4]=a[3]
        a[3]=b
        return a
    else
        a[4]=b[3]
        b[3]=a
        return b
    end
end

PairingHeap.pair=function(self,a)
    local b,c,d,e
    while a do
        c=false
        b=a
        a=a[4]
        b[4]=false
        if a then
            c=a
            a=a[4]
            c[4]=false
        end
        b=self:meld(b,c)
        b[4]=d
        d=b
    end
    while d do
        e=d
        d=d[4]
        a=self:meld(a,e)
    end
    return a
end

PairingHeap.empty=function(self)
    return not self.root
end

PairingHeap.push=function(self,key,value)
    local root=self.root
    if root and root[1]<key then
        root[3]={
            key,
            value,
            false,
            root[3],
        }
    else
        self.root={
            key,
            value,
            root,
            false,
        }
    end
end

PairingHeap.top=function(self)
	return self.root[2]
end

PairingHeap.pop=function(self)
    local root=self.root
    self.root=self:pair(root[3])
    for i=1,4 do
        root[i]=false
    end
    table.insert(self,root)
end

PairingHeap.join=function(self,other)
    local a=self.root
    local b=other.root
    if a[1]<b[1]then
        b[4]=a[3]
        a[3]=b
    else
        a[4]=b[3]
        b[3]=a
        self.root=b
    end
    return self
end

PairingHeap.new=function(self)
    local obj={}
    setmetatable(obj,{__index=PairingHeap})
    return obj
end

----------

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

local lsum={[0]=0}
local minq=PairingHeap:new()
for i=1,n do
    local A=a[i]
    lsum[i]=lsum[i-1]+A
    minq:push(A,A)
end
for i=n+1,2*n do
    local P=minq:top()
    local A=a[i]
    if A>P then
        lsum[i]=lsum[i-1]+A-P
        minq:push(A,A)
        minq:pop()
    else
        lsum[i]=lsum[i-1]
    end
end

local rsum={[0]=0}
local maxq=PairingHeap:new()
for i=1,n do
    local A=a[3*n-i+1]
    rsum[i]=rsum[i-1]+A
    maxq:push(-A,A)
end
for i=n+1,2*n do
    local P=maxq:top()
    local A=a[3*n-i+1]
    if A<P then
        rsum[i]=rsum[i-1]+A-P
        maxq:push(-A,A)
        maxq:pop()
    else
        rsum[i]=rsum[i-1]
    end
end
local max=-10^16
for i=n,2*n do
    max=math.max(max,lsum[i]-rsum[3*n-i])
end
print(max)

Score : 500 points

Problem Statement

Let N be a positive integer.

There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}).
Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements.
Here, the score of a' is defined as follows: (the sum of the elements in the first half of a') - (the sum of the elements in the second half of a').

Find the maximum possible score of a'.

Constraints

1 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Partial Score

In the test set worth 300 points, N ≤ 1000.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the maximum possible score of a'.

Sample Input 1

2
3 1 4 1 5 9

Sample Output 1

1

When a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3 + 4) - (1 + 5) = 1.

Sample Input 2

1
1 2 3

Sample Output 2

-1

For example, when a_1 are removed, a' will be (2, 3), which has a score of 2 - 3 = -1.

Sample Input 3

3
8 2 2 7 4 6 5 3 8

Sample Output 3

5

For example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3), which has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5.


local PairingHeap={}

PairingHeap.meld=function(self,a,b)
    if not a then
        return b
    elseif not b then
        return a
    elseif a[1]<b[1] then
        b[4]=a[3]
        a[3]=b
        return a
    else
        a[4]=b[3]
        b[3]=a
        return b
    end
end

PairingHeap.pair=function(self,a)
    local b,c,d,e
    while a do
        c=false
        b=a
        a=a[4]
        b[4]=false
        if a then
            c=a
            a=a[4]
            c[4]=false
        end
        b=self:meld(b,c)
        b[4]=d
        d=b
    end
    while d do
        e=d
        d=d[4]
        a=self:meld(a,e)
    end
    return a
end

PairingHeap.empty=function(self)
    return not self.root
end

PairingHeap.push=function(self,key,value)
    local root=self.root
    if root and root[1]<key then
        root[3]={
            key,
            value,
            false,
            root[3],
        }
    else
        self.root={
            key,
            value,
            root,
            false,
        }
    end
end

PairingHeap.pop=function(self)
    local root=self.root
    local value=root[2]
    self.root=self:pair(root[3])
    for i=1,4 do
        root[i]=false
    end
    table.insert(self,root)
    return value
end

PairingHeap.join=function(self,other)
    local a=self.root
    local b=other.root
    if a[1]<b[1]then
        b[4]=a[3]
        a[3]=b
    else
        a[4]=b[3]
        b[3]=a
        self.root=b
    end
    return self
end

PairingHeap.new=function(self)
    local obj={}
    setmetatable(obj,{__index=PairingHeap})
    return obj
end

----------

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

local lsum={[0]=0}
local minq=PairingHeap:new()
for i=1,n do
    local A=a[i]
    lsum[i]=lsum[i-1]+A
    minq:push(A,A)
end
for i=n+1,2*n do
    local X=a[i]-minq:pop()
    lsum[i]=lsum[i-1]+(X>0 and X or 0)
end

local rsum={[0]=0}
local maxq=PairingHeap:new()
for i=1,n do
    local A=a[3*n-i+1]
    rsum[i]=rsum[i-1]+A
    maxq:push(-A,A)
end
for i=n+1,2*n do
    local X=a[3*n-i+1]-maxq:pop()
    rsum[i]=rsum[i-1]+(X<0 and X or 0)
end
local max=math.mininteger
for i=n+1,2*n do
    max=math.max(max,lsum[i]-rsum[3*n-i])
end
print(max)


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

local h, w = io.read("*n", "*n", "*l")
local idxedges = {}
local sidx, gidx = 0, 0

--[[
1, ..., w: column i
w + 1, ..., w + h: row i
w + h + 1: startpos
w + h + 2: goalpos
]]
local snode = w + h + 1
local gnode = w + h + 2
local edge = {}
for i = 1, gnode do
  edge[i] = {}
end

for i = 1, h do
  local str = io.read()
  for j = 1, w do
    local idx = (i - 1) * w + j
    local s = str:sub(j, j)
    if s == "S" then
      sidx = idx
    elseif s == "T" then
      gidx = idx
    elseif s == "o" then
      table.insert(idxedges, idx)
    end
  end
end
local function getrowcol(idx)
  local r = 1 + mfl((idx - 1) / w)
  local c = idx % w
  if c == 0 then c = w end
  return r, c
end

local len, stlen = {}, {}
for i = 1, gnode + 1 do
  len[i] = gnode
  stlen[i] = gnode
end
local seg = SegTree.new(gnode, function(x, y) return stlen[x] < stlen[y] and x or y end)

local function runDijkstra()
  for i = 1, gnode + 1 do
    len[i] = gnode
    stlen[i] = gnode
  end
  len[snode] = 0
  stlen[snode] = 0
  seg:updateAll()
  for i = 1, gnode do
    local node = seg.stage[1][1]
    if gnode <= stlen[node] then
      break
    end
    for dst, v in pairs(edge[node]) do
      if len[node] + 1 < len[dst] then
        len[dst] = len[node] + 1
        stlen[dst] = stlen[node] + 1
        seg:update(dst)
      end
    end
    stlen[node] = gnode
    seg:update(node)
  end
  if gnode <= len[gnode] then
    return false
  else
    -- reverse walk
    local cur = gnode
    while cur ~= snode do
      for dst, v in pairs(edge[cur]) do
        if v and len[dst] + 1 == len[cur] then
          edge[cur][dst] = edge[cur][dst] - 1
          edge[dst][cur] = edge[dst][cur] - 1
          if edge[cur][dst] == 0 then
            edge[cur][dst] = nil
            edge[dst][cur] = nil
          end
          cur = dst
          break
        end
      end
    end
    return true
  end
end

local function solve()
  local sr, sc = getrowcol(sidx)
  local gr, gc = getrowcol(gidx)
  if sr == gr or sc == gc then
    return -1
  end
  local idxedgenum = #idxedges
  local function addedge(a, b)
    if not edge[a][b] then edge[a][b] = 1
    else edge[a][b] = edge[a][b] + 1 end
    if not edge[b][a] then edge[b][a] = 1
    else edge[b][a] = edge[b][a] + 1 end
  end
  for i = 1, idxedgenum do
    local r, c = getrowcol(idxedges[i])
    if r == sr then
      if c == gc then
        addedge(snode, gnode)
      else
        addedge(snode, c)
      end
    elseif r == gr then
      if c == sc then
        addedge(snode, gnode)
      else
        addedge(gnode, c)
      end
    else
      if c == sc then
        addedge(snode, r + w)
      elseif c == gc then
        addedge(gnode, r + w)
      else
        addedge(c, r + w)
      end
    end
  end
  local cnt = 0
  while true do
    if runDijkstra() then
      cnt = cnt + 1
    else
      break
    end
  end
  return cnt
end
print(solve())

Score : 800 points

Problem Statement

There is a pond with a rectangular shape.
The pond is divided into a grid with H rows and W columns of squares.
We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).

Some of the squares in the pond contains a lotus leaf floating on the water.
On one of those leaves, S, there is a frog trying to get to another leaf T.
The state of square (i,\ j) is given to you by a character a_{ij}, as follows:

. : A square without a leaf.

o : A square with a leaf floating on the water.

S : A square with the leaf S.

T : A square with the leaf T.

The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."

Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T.
Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.

Constraints

2 ≤ H, W ≤ 100

a_{ij} is ., o, S or T.

There is exactly one S among a_{ij}.

There is exactly one T among a_{ij}.

Input

Input is given from Standard Input in the following format:

H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}

Output

If the objective is achievable, print the minimum necessary number of leaves to remove.
Otherwise, print -1 instead.

Sample Input 1

3 3
S.o
.o.
o.T

Sample Output 1

2

Remove the upper-right and lower-left leaves.

Sample Input 2

3 4
S...
.oo.
...T

Sample Output 2

0

Sample Input 3

4 3
.S.
.o.
.o.
.T.

Sample Output 3

-1

Sample Input 4

10 10
.o...o..o.
....o.....
....oo.oo.
..oooo..o.
....oo....
..o..o....
o..o....So
o....T....
....o.....
........oo

Sample Output 4

5


a, b, c = io.read("*n", "*n", "*n")
if a <= c and c <= b then
  print("Yes")
else
  print("No")
end

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


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

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2


local n,k=io.read("n","n")
local t={}
for i=1,n do
    local a,b=io.read("n","n")
    t[i]={a,b}
end
table.sort(t,function(x,y)
    return x[1]<y[1]
end)

local counter=0
for i=1,n do
    counter=counter+t[i][2]
    if counter>=k then
        print(t[i][1])
        return
    end
end

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


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

local taskstate = {}
for i = 1, n do taskstate[i] = false end
local tasks = {}
local tasknum = 0
local done = 0
local tasklim = n + 1
local updatecount = 0
local len = {}
for i = 1, n do len[i] = -1000000000000 end
len[1] = 0
local function addtask(idx)
  if(not taskstate[idx]) then
    taskstate[idx] = true
    tasknum = tasknum + 1
    local taskidx = tasknum % tasklim
    if taskidx == 0 then taskidx = tasklim end
    tasks[taskidx] = idx
    if idx == n then
      updatecount = updatecount + 1
      if n + 2 < updatecount then
        return false
      end
    end
  end
  return true
end
addtask(1)

local ret = true
while(done < tasknum) do
  done = done + 1
  local taskidx = done % tasklim
  if(taskidx == 0) then taskidx = tasklim end
  local src = tasks[taskidx]
  taskstate[src] = false

  for dst, cost in pairs(edge[src]) do
    if len[dst] < len[src] + cost then
      len[dst] = len[src] + cost
      ret = addtask(dst)
    end
  end
  if not ret then break end
  if 10000000 < done then break end
end
if ret then
  print(len[n])
else
  print("inf")
end

Score : 400 points

Problem Statement

There is a directed graph with N vertices and M edges.
The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i.
We will play the following single-player game using this graph and a piece.

Initially, the piece is placed at vertex 1, and the score of the player is set to 0.
The player can move the piece as follows:

When the piece is placed at vertex a_i, move the piece along the i-th edge to vertex b_i. After this move, the score of the player is increased by c_i.

The player can end the game only when the piece is placed at vertex N.
The given graph guarantees that it is possible to traverse from vertex 1 to vertex N.

When the player acts optimally to maximize the score at the end of the game, what will the score be?
If it is possible to increase the score indefinitely, print inf.

Constraints

2≤N≤1000

1≤M≤min(N(N-1),2000)

1≤a_i,b_i≤N (1≤i≤M)

a_i≠b_i (1≤i≤M)

a_i≠a_j or b_i≠b_j (1≤i<j≤M)

-10^9≤c_i≤10^9 (1≤i≤M)

c_i is an integer.

In the given graph, there exists a path from vertex 1 to vertex N.

Input

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 maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.

Sample Input 1

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

7

There are two ways to move the piece to vertex N=3:

vertex 1 → vertex 2 → vertex 3 : score 4+3=7

vertex 1 → vertex 3 : score 5

Thus, the maximum possible score at the end of the game is 7.

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

inf

It is possible to increase the score indefinitely by alternating between vertex 1 and 2.

Sample Input 3

6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Sample Output 3

-5000000000


n,m=io.read("*n","*n")
d={}
e=-1e15
for i=1,n do
	d[i]={}
	for j=1,n do
		d[i][j]=(i==j and 0 or e)
	end
end

for i=1,m do
	a,b,c=io.read("*n","*n","*n")
	d[a][b]=c
end

for k=n,1,-1 do
	for i=1,n do
		c=d[i][k]
		if c~=e then
			for j=1,n do
				a=c+d[k][j]
				b=d[i][j]
				if b<a then d[i][j]=a end
			end
		end
	end
end

print(d[1][1]>0 and"inf"or d[1][n])


local n,m=io.read("n","n")
local t={}
for i=1,m do
	local a,b=io.read("n","n")
	t[a]=((t[a] or 0)+1)%2
	t[b]=((t[b] or 0)+1)%2
end
local checker=0
for i=1,n do
	checker=checker+(t[i] or 0)
end
print(checker>0 and "NO" or "YES")

Score : 500 points

Problem Statement

Takahashi is not good at problems about trees in programming contests, and Aoki is helping him practice.

First, Takahashi created a tree with N vertices numbered 1 through N, and wrote 0 at each edge.

Then, Aoki gave him M queries. The i-th of them is as follows:

Increment the number written at each edge along the path connecting vertices a_i and b_i, by one.

After Takahashi executed all of the queries, he told Aoki that, for every edge, the written number became an even number.
However, Aoki forgot to confirm that the graph Takahashi created was actually a tree, and it is possible that Takahashi made a mistake in creating a tree or executing queries.

Determine whether there exists a tree that has the property mentioned by Takahashi.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

1 ≤ a_i,b_i ≤ N

a_i ≠ b_i

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print YES if there exists a tree that has the property mentioned by Takahashi; print NO otherwise.

Sample Input 1

4 4
1 2
2 4
1 3
3 4

Sample Output 1

YES

For example, Takahashi's graph has the property mentioned by him if it has the following edges: 1-2, 1-3 and 1-4.
In this case, the number written at every edge will become 2.

Sample Input 2

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

Sample Output 2

NO


local mmi = math.min
local h, w, k = io.read("*n", "*n", "*n", "*l")
local t = {}
local inf = 1000000007
local spos = 0
local len = {}
for i = 1, h do
  local str = io.read()
  for j = 1, w do
    local idx = (i - 1) * w + j
    local ss = str:sub(j, j)
    t[idx] = not (ss == "#")
    len[idx] = inf
    if ss == "S" then
      spos = idx
    end
  end
end

local taskstate = {}
for i = 1, h * w do taskstate[i] = false end
local tasks = {}
local tasknum = 0
local done = 0
local tasklim = h * w

local function addtask(idx)
  if not taskstate[idx] then
    taskstate[idx] = true
    tasknum = tasknum + 1
    local taskidx = tasknum % tasklim
    if taskidx == 0 then taskidx = tasklim end
    tasks[taskidx] = idx
  end
end

local function walk(src, dst)
  if t[dst] and len[src] < k and len[src] + 1 < len[dst] then
    len[dst] = len[src] + 1
    addtask(dst)
  end
end

len[spos] = 0
addtask(spos)

while done < tasknum do
  done = done + 1
  local taskidx = done % tasklim
  if taskidx == 0 then taskidx = tasklim end
  local idx = tasks[taskidx]
  taskstate[idx] = false

  if w < idx then walk(idx, idx - w) end
  if idx <= (h - 1) * w then walk(idx, idx + w) end
  if idx % w ~= 0 then walk(idx, idx + 1) end
  if idx % w ~= 1 then walk(idx, idx - 1) end
end

local ret = inf

for i = 1, h do
  for j = 1, w do
    local idx = (i - 1) * w + j
    if len[idx] <= k then
      local cand = mmi(i - 1, h - i)
      cand = mmi(cand, j - 1)
      cand = mmi(cand, w - j)
      ret = mmi(ret, 1 + math.ceil(cand / k))
    end
  end
end
print(ret)

Score : 700 points

Problem Statement

Takahashi is locked within a building.

This building consists of H×W rooms, arranged in H rows and W columns.
We will denote the room at the i-th row and j-th column as (i,j). The state of this room is represented by a character A_{i,j}. If A_{i,j}= #, the room is locked and cannot be entered; if A_{i,j}= ., the room is not locked and can be freely entered.
Takahashi is currently at the room where A_{i,j}= S, which can also be freely entered.

Each room in the 1-st row, 1-st column, H-th row or W-th column, has an exit.
Each of the other rooms (i,j) is connected to four rooms: (i-1,j), (i+1,j), (i,j-1) and (i,j+1).

Takahashi will use his magic to get out of the building. In one cast, he can do the following:

Move to an adjacent room at most K times, possibly zero. Here, locked rooms cannot be entered.

Then, select and unlock at most K locked rooms, possibly zero. Those rooms will remain unlocked from then on.

His objective is to reach a room with an exit. Find the minimum necessary number of casts to do so.

It is guaranteed that Takahashi is initially at a room without an exit.

Constraints

3 ≤ H ≤ 800

3 ≤ W ≤ 800

1 ≤ K ≤ H×W

Each A_{i,j} is # , . or S.

There uniquely exists (i,j) such that A_{i,j}= S, and it satisfies 2 ≤ i ≤ H-1 and 2 ≤ j ≤ W-1.

Input

Input is given from Standard Input in the following format:

H W K
A_{1,1}A_{1,2}...A_{1,W}
:
A_{H,1}A_{H,2}...A_{H,W}

Output

Print the minimum necessary number of casts.

Sample Input 1

3 3 3
#.#
#S.
###

Sample Output 1

1

Takahashi can move to room (1,2) in one cast.

Sample Input 2

3 3 3
###
#S#
###

Sample Output 2

2

Takahashi cannot move in the first cast, but can unlock room (1,2).
Then, he can move to room (1,2) in the next cast, achieving the objective in two casts.

Sample Input 3

7 7 2
#######
#######
##...##
###S###
##.#.##
###.###
#######

Sample Output 3

2


Score : 100 points

Problem Statement

You are given three strings A, B and C. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in A and the initial character in B are the same.

The last character in B and the initial character in C are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

A, B and C are all composed of lowercase English letters (a - z).

1 ≤ |A|, |B|, |C| ≤ 10, where |A|, |B| and |C| are the lengths of A, B and C, respectively.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

A and B form a word chain, but B and C do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


N,T=io.read("n","n")
t1=io.read("n")
ans=0
prev=0
for i=2,N do
  ti = io.read("n")
  dur = ti - prev
  ans = ans + (dur > T and T or dur)
  prev = ti
end
ans = ans + T
print(ans)

Score : 300 points

Problem Statement

In a public bath, there is a shower which emits water for T seconds when the switch is pushed.

If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds.
Note that it does not mean that the shower emits water for T additional seconds.

N people will push the switch while passing by the shower.
The i-th person will push the switch t_i seconds after the first person pushes it.

How long will the shower emit water in total?

Constraints

1 ≤ N ≤ 200,000

1 ≤ T ≤ 10^9

0 = t_1 < t_2 < t_3 < , ..., < t_{N-1} < t_N ≤ 10^9

T and each t_i are integers.

Input

Input is given from Standard Input in the following format:

N T
t_1 t_2 ... t_N

Output

Assume that the shower will emit water for a total of X seconds. Print X.

Sample Input 1

2 4
0 3

Sample Output 1

7

Three seconds after the first person pushes the water, the switch is pushed again and the shower emits water for four more seconds, for a total of seven seconds.

Sample Input 2

2 4
0 5

Sample Output 2

8

One second after the shower stops emission of water triggered by the first person, the switch is pushed again.

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67


N,T=io.read("n","n")
t1=io.read("n")
ans=0
for i=2,N do
  ti = io.read("n")
  ans = ans + (ti > T and T or ti)
end
ans = ans + T
print(ans)


local n, t = io.read("*n", "*n", "*l")
local str = io.read()
local a = {}
for numstr in string.gmatch(str, "%d+") do
  table.insert(a, tonumber(numstr))
end
local totlen = a[#a] + t
for i = 2, n do
  totlen = totlen - math.max(0, a[i] - a[i - 1] - t)
end
print(totlen)


local mmi, mma = math.min, math.max
local n = io.read("*n")
local a, b = {}, {}
local ta, tb = io.read("*n"), io.read("*n")
if tb < ta then ta, tb = tb, ta end
local a, b = {ta}, {tb}
local minv, minp, maxv, maxp = ta, 1, tb, 1
for i = 2, n do
  ta, tb= io.read("*n", "*n")
  if tb < ta then ta, tb = tb, ta end
  a[i], b[i] = ta, tb
  if ta < minv then
    minv = ta
    minp = i
  end
  if maxv < tb then
    maxv = tb
    maxp = i
  end
end
local ret = nil
if minv == maxv then
  -- (A) all same
  ret = 0
else
  -- (B) R has min, B has max value
  local redmax, bluemin = a[1], b[1]
  for i = 2, n do
    redmax = mma(redmax, a[i])
    bluemin = mmi(bluemin, b[i])
  end
  ret = (redmax - minv) * (maxv - bluemin)
end

-- (C) R has both of min and max values
do
  local t = {}
  for i = 1, n do t[i] = i end
  table.sort(t, function(x, y) return a[x] < a[y] end)
  local bmin = nil
  local bmax = nil
  local minlen = a[t[n]] - a[t[1]]
  for i = 1, n do
    if i == 1 then
      bmin, bmax = b[t[1]], b[t[1]]
    else
      bmin = mmi(bmin, b[t[i]])
      bmax = mma(bmax, b[t[i]])
    end
    local l = i == n and bmin or mmi(a[t[i + 1]], bmin)
    local r = i == n and bmax or mma(a[t[n]], bmax)
    minlen = mmi(minlen, r - l)
  end
  ret = mmi(ret, minlen * (maxv - minv))
end
print(ret)

Score : 700 points

Problem Statement

There are N bags, each containing two white balls. The i-th box contains two balls with integers x_i and y_i written on them, respectively.

For each of these bags, you will paint one of the balls red, and paint the other blue.

Afterwards, the 2N balls will be classified according to color.

Then, we will define the following:

R_{max}: the maximum integer written on a ball painted in red

R_{min}: the minimum integer written on a ball painted in red

B_{max}: the maximum integer written on a ball painted in blue

B_{min}: the minimum integer written on a ball painted in blue

Find the minimum possible value of (R_{max} - R_{min}) \times (B_{max} - B_{min}).

Constraints

1 ≤ N ≤ 200,000

1 ≤ x_i, y_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the minimum possible value.

Sample Input 1

3
1 2
3 4
5 6

Sample Output 1

15

The optimal solution is to paint the balls with x_1, x_2, y_3 red, and paint the balls with y_1, y_2, x_3 blue.

Sample Input 2

3
1010 10
1000 1
20 1020

Sample Output 2

380

Sample Input 3

2
1 1
1000000000 1000000000

Sample Output 3

999999998000000001


function f(x)
  return(x:match("^."))
end
a=io.read()
print(string.upper(a:gsub("%l+",f):gsub("%s","")))

Score : 100 points

Problem Statement

You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between.
Print the acronym formed from the uppercased initial letters of the words.

Constraints

s_1, s_2 and s_3 are composed of lowercase English letters.

1 ≤ |s_i| ≤ 10 (1≤i≤3)

Input

Input is given from Standard Input in the following format:

s_1 s_2 s_3

Output

Print the answer.

Sample Input 1

atcoder beginner contest

Sample Output 1

ABC

The initial letters of atcoder, beginner and contest are a, b and c. Uppercase and concatenate them to obtain ABC.

Sample Input 2

resident register number

Sample Output 2

RRN

Sample Input 3

k nearest neighbor

Sample Output 3

KNN

Sample Input 4

async layered coding

Sample Output 4

ALC


A = tostring(io.read())
B = tostring(io.read())
if #A>#B then
    print("GREATER")
elseif #A<#B then
    print("LESS")
elseif #A==#B then
    i = 1
    while A:sub(i,i) == B:sub(i,i) and i<#A do
        i = i+1
    end
    if A:sub(i,i) > B:sub(i,i) then
        print("GREATER")
    elseif A:sub(i,i) < B:sub(i,i) then
        print("LESS")
    elseif A:sub(i,i) == B:sub(i,i) then
        print("EQUAL")
    end
end

Score : 200 points

Problem Statement

You are given two positive integers A and B. Compare the magnitudes of these numbers.

Constraints

1 ≤ A, B ≤ 10^{100}

Neither A nor B begins with a 0.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print GREATER if A>B, LESS if A<B and EQUAL if A=B.

Sample Input 1

36
24

Sample Output 1

GREATER

Since 36>24, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


a=io.read()
b=io.read()
a=string.rep("0",101-#a)..a
b=string.rep("0",101-#b)..b
print(a==b and "EQUAL" or a>b and "GREATER" or "LESS")


local n = io.read("*n", "*l")
local str = io.read()
local a = {}
for v in str:gmatch("(%-?%d+)") do
  table.insert(a, tonumber(v))
end
local stepmin = nil
for type = -1, 1, 2 do
  local step = 0
  local sum = 0
  local flag = type
  for i = 1, n do
    sum = sum + a[i]
    if flag == 1 then
      if sum <= 0 then
        step = step + 1 - sum
        sum = 1
      end
    else
      if 0 <= sum then
        step = step + 1 + sum
        sum = -1
      end
    end
    flag = -flag
  end
  if type == -1 then stepmin = step else stepmin = math.min(stepmin, step) end
end
print(stepmin)

Score : 300 points

Problem Statement

You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.

For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each a_i is an integer.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print the minimum necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8


a, b = io.read("*n", "*n")
print(math.abs(a-b) <= 1 and "Brown" or "Alice")

Score : 500 points

Problem Statement

Alice and Brown loves games. Today, they will play the following game.

In this game, there are two piles initially consisting of X and Y stones, respectively.
Alice and Bob alternately perform the following operation, starting from Alice:

Take 2i stones from one of the piles. Then, throw away i of them, and put the remaining i in the other pile. Here, the integer i (1≤i) can be freely chosen as long as there is a sufficient number of stones in the pile.

The player who becomes unable to perform the operation, loses the game.

Given X and Y, determine the winner of the game, assuming that both players play optimally.

Constraints

0 ≤ X, Y ≤ 10^{18}

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the winner: either Alice or Brown.

Sample Input 1

2 1

Sample Output 1

Brown

Alice can do nothing but taking two stones from the pile containing two stones. As a result, the piles consist of zero and two stones, respectively. Then, Brown will take the two stones, and the piles will consist of one and zero stones, respectively. Alice will be unable to perform the operation anymore, which means Brown's victory.

Sample Input 2

5 0

Sample Output 2

Alice

Sample Input 3

0 0

Sample Output 3

Brown

Sample Input 4

4 8

Sample Output 4

Alice


N = io.read "l"
sum = 0
op = 0
for a in io.read "l":gmatch "%-?%d+" do
    a = tonumber(a)
    if sum > 0 then
        if a >= -sum then
            aNew = -sum - 1
            op = op + math.abs(a - aNew)
            a = aNew
        end
    elseif sum < 0 then
        if a <= -sum then
            aNew = -sum + 1
            op = op + math.abs(a - aNew)
            a = aNew
        end
    end
    sum = sum + a
end
print(("%d"):format(op))


N = io.read "l"
sum = 0
op = 0
for a in io.read "l":gmatch "%-?%d+" do
    a = tonumber(a)
    if sum > 0 then
        if a >= -sum then
            aNew = -sum - 1
            op = op + math.abs(a - aNew)
            a = aNew
        end
    elseif sum < 0 then
        if a <= -sum then
            aNew = -sum + 1
            op = op + math.abs(a - aNew)
            a = aNew
        end
    end
    sum = sum + a
end
print(op)


status=0
split=0
n=io.read("*n")
a=io.read("*n")
for i=1,n-1 do
    b=io.read("*n")
    if a>b then
        if status==1 then
            split=split+1
            status=0
        elseif status==0 then
            status=-1
        end
    elseif a<b then
        if status==-1 then
            split=split+1
            status=0
        elseif status==0 then
            status=1
        end
    end
    a=b
end
print(split+1)

Score : 300 points

Problem Statement

You are given an array A of length N.
Your task is to divide it into several contiguous subarrays.
Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order.
At least how many subarrays do you need to divide A into?

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Each A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible number of subarrays after division of A.

Sample Input 1

6
1 2 3 2 2 1

Sample Output 1

2

One optimal solution is to divide the array into [1,2,3] and [2,2,1].

Sample Input 2

9
1 2 1 2 1 2 1 2 1

Sample Output 2

5

Sample Input 3

7
1 2 3 2 1 999999999 1000000000

Sample Output 3

3


local n = io.read("*n", "*l")
local a, b = {}, {}
for i = 1, n do
  local s = io.read()
  a[i] = s:gsub("?", "a")
  b[i] = s:gsub("?", "z")
end
table.sort(a)
table.sort(b)
local t = io.read()
local min = n + 1
for i = n, 1, -1 do
  if b[i] < t then
    break
  else
    min = i
  end
end
local max = 1
for i = 1, n do
  if t < a[i] then
    break
  else
    max = i + 1
  end
end
for k = min, max do
  io.write(k)
  io.write(k == max and "\n" or " ")
end

Max Score: 250 Points

Problem Statement

Mr.X, who the handle name is T, looked at the list which written N handle names, S_1, S_2, ..., S_N.

But he couldn't see some parts of the list. Invisible part is denoted ?.

Please calculate all possible index of the handle name of Mr.X when you sort N+1 handle names (S_1, S_2, ..., S_N and T) in lexicographical order.

Note: If there are pair of people with same handle name, either one may come first.

Input

The input is given from standard input in the following format.

N
S_1
S_2
:
S_N
T

Output

Calculate the possible index and print in sorted order. The output should be separated with a space. Don't print a space after last number.

Put a line break in the end.

Constraints

1 ≤ N ≤ 10000

1 ≤ |S_i|, |T| ≤ 20 (|A| is the length of A.)

S_i consists from lower-case alphabet and ?.

T consists from lower-case alphabet.

Scoring

Subtask 1 [ 130 points ]

There are no ?'s.

Subtask 2 [ 120 points ]

There are no additional constraints.

Sample Input 1

2
tourist
petr
e

Sample Output 1

1

There are no invisible part, so there are only one possibility.
The sorted handle names are e, petr, tourist, so e comes first.

Sample Input 2

2
?o?r?s?
?et?
e


local mmi, mma = math.min, math.max
local function combination_get_map(n)
  local combmap = {}
  for i = 1, n do
    combmap[i] = {}
    local ret = 1
    for j = 1, i do
      ret = ret * (i + 1 - j) // j
      combmap[i][j] = ret
    end
  end
  return combmap
end
local function combination_get_count(combmap, n, k)
  if k < 0 then return 0
  elseif n < k then return 0
  elseif k == 0 then return 1
  else return combmap[n][k]
  end
end

local function combination_get_array(combmap, n, k, idx)
  local rem = k
  local retary = {}
  for i = 1, n do
    local useCnt = combination_get_count(combmap, n - i, rem - 1)
    local unuseCnt = combination_get_count(combmap, n - i, rem)
    if idx <= useCnt then
      rem = rem - 1
      table.insert(retary, i)
    else
      idx = idx - useCnt
    end
  end
  return retary
end

local n, k = io.read("*n", "*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
local cmap = combination_get_map(n)
local tot = combination_get_count(cmap, n, k)
local mincost = 1000000007 * 100
for i = 1, tot do
  local cost = 0
  local ary = combination_get_array(cmap, n, k, i)
  local height = a[1]
  for j = 2, ary[1] do
    height = mma(height, a[j])
  end
  for j = 2, k do
    local pos = ary[j]
    for z = ary[j - 1] + 1, pos - 1 do
      height = mma(height, a[z])
    end
    local v = a[pos]
    if height < v then
      height = v
    else
      cost = cost + height + 1 - v
      height = height + 1
    end
  end
  mincost = mmi(mincost, cost)
end
print(mincost)

Max Score: 350 Points

Problem Statement

There are N buildings along the line. The i-th building from the left is colored in color i, and its height is currently a_i meters.

Chokudai is a mayor of the city, and he loves colorful thigs. And now he wants to see at least K buildings from the left.

You can increase height of buildings, but it costs 1 yens to increase 1 meters. It means you cannot make building that height is not integer.

You cannot decrease height of buildings.

Calculate the minimum cost of satisfying Chokudai's objective.

Note: "Building i can see from the left" means there are no j exists that (height of building j) ≥ (height of building i) and j < i.

Input Format

N K
a_1 a_2 a_3 ... a_N

Output Format

Print the minimum cost in one line. In the end put a line break.

Constraints

1 ≤ K ≤ N ≤ 15

1 ≤ a_i ≤ 10^9

Scoring

Subtask 1 [120 points]

N = K

Subtask 2 [90 points]

N ≤ 5

a_i ≤ 7

Subtask 3 [140 points]

There are no additional constraints.

Sample Input 1

5 5
3949 3774 3598 3469 3424

Sample Output 1

1541

The optimal solution is (height of buildings from the left) = [3949, 3950, 3951, 3952, 3953].

Sample Input 2

5 3
7 4 2 6 4

Sample Output 2

7

The optimal solution is (height of buildings from the left) = [7, 8, 2, 9, 4].


a, b, c = io.read("*n", "*n", "*n")
print((b - a) == (c - b) and "YES" or "NO")

Score : 100 points

Problem Statement

Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right.
We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b.

Determine whether the arrangement of the poles is beautiful.

Constraints

1 \leq a,b,c \leq 100

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

Print YES if the arrangement of the poles is beautiful; print NO otherwise.

Sample Input 1

2 4 6

Sample Output 1

YES

Since 4-2 = 6-4, this arrangement of poles is beautiful.

Sample Input 2

2 5 6

Sample Output 2

NO

Since 5-2 \neq 6-5, this arrangement of poles is not beautiful.

Sample Input 3

3 2 1

Sample Output 3

YES

Since 1-2 = 2-3, this arrangement of poles is beautiful.


n = io.read("*n", "*l")
t = {}
for i = 1, n do
    u = {}
    for j = 0, 25 do u[string.char(97 + j)] = 0 end
    s = io.read()
    len = string.len(s)
    for j = 1, len do
        a = string.sub(s, j, j)
        u[a] = u[a] + 1
    end
    for j = 0, 25 do
        moji = string.char(97 + j)
        if(t[moji] == nil) then t[moji] = u[moji] else t[moji] = math.min(t[moji], u[moji]) end
    end
end
for i = 0, 25 do
    moji = string.char(97 + i)
    if(t[moji] ~= nil) then
        for j = 1, t[moji] do
            io.write(moji)
        end
    end
end
io.write("\n")

Score : 300 points

Problem Statement

Snuke loves "paper cutting": he cuts out characters from a newspaper headline and rearranges them to form another string.

He will receive a headline which contains one of the strings S_1,...,S_n tomorrow.
He is excited and already thinking of what string he will create.
Since he does not know the string on the headline yet, he is interested in strings that can be created regardless of which string the headline contains.

Find the longest string that can be created regardless of which string among S_1,...,S_n the headline contains.
If there are multiple such strings, find the lexicographically smallest one among them.

Constraints

1 \leq n \leq 50

1 \leq |S_i| \leq 50 for every i = 1, ..., n.

S_i consists of lowercase English letters (a - z) for every i = 1, ..., n.

Input

Input is given from Standard Input in the following format:

n
S_1
...
S_n

Output

Print the lexicographically smallest string among the longest strings that satisfy the condition.
If the answer is an empty string, print an empty line.

Sample Input 1

3
cbaa
daacc
acacac

Sample Output 1

aac

The strings that can be created from each of cbaa, daacc and acacac, are aa, aac, aca, caa and so forth.
Among them, aac, aca and caa are the longest, and the lexicographically smallest of these three is aac.

Sample Input 2

3
a
aa
b

Sample Output 2

The answer is an empty string.


local n,m = io.read("*n", "*n")
local xsum,ysum,mod=0,0,1000000007
for i=0,n-1 do
  local x=io.read("*n")
  xsum = xsum + x*(i-(n-1-i))
  xsum=xsum%mod
end
for i=0,m-1 do
  local y=io.read("*n")
  ysum = ysum + y*(i-(m-1-i))
  ysum=ysum%mod
end
print(xsum*ysum%mod)

Score : 500 points

Problem Statement

On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis.
Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i.
Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i.

For every rectangle that is formed by these lines, find its area, and print the total area modulo 10^9+7.

That is, for every quadruple (i,j,k,l) satisfying 1\leq i < j\leq n and 1\leq k < l\leq m, find the area of the rectangle formed by the lines x=x_i, x=x_j, y=y_k and y=y_l, and print the sum of these areas modulo 10^9+7.

Constraints

2 \leq n,m \leq 10^5

-10^9 \leq x_1 < ... < x_n \leq 10^9

-10^9 \leq y_1 < ... < y_m \leq 10^9

x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

n m
x_1 x_2 ... x_n
y_1 y_2 ... y_m

Output

Print the total area of the rectangles, modulo 10^9+7.

Sample Input 1

3 3
1 3 4
1 3 6

Sample Output 1

60

The following figure illustrates this input:

The total area of the nine rectangles A, B, ..., I shown in the following figure, is 60.

Sample Input 2

6 5
-790013317 -192321079 95834122 418379342 586260100 802780784
-253230108 193944314 363756450 712662868 735867677

Sample Output 2

835067060


local n,m = io.read("*n", "*n")
local xsum, ysum=0, 0
for i=0,n-1 do
  local x=io.read("*n")
  xsum = xsum + x*(i-(n-1-i))
end
for i=0,m-1 do
  local y=io.read("*n")
  ysum = ysum + y*(i-(m-1-i))
end
xsum=xsum%(1e9+7)
ysum=ysum%(1e9+7)
print(math.floor(xsum*ysum%(1e9+7)))


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.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.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local function merge(x, y)
  return (x + y) % 3
end

local s = io.read()
local t = io.read()
local sts = SegTree.new(#s, merge, 0)
for i = 1, #s do
  sts:setValue(i, s:sub(i, i):byte() - 64, true)
end
sts:updateAll()
local stt = SegTree.new(#t, merge, 0)
for i = 1, #t do
  stt:setValue(i, t:sub(i, i):byte() - 64, true)
end
stt:updateAll()
local q = io.read("*n")
for iq = 1, q do
  local a, b, c, d = io.read("*n", "*n", "*n", "*n")
  print(sts:getRange(a, b) == stt:getRange(c, d) and "YES" or "NO")
end

Score : 600 points

Problem Statement

Let us consider the following operations on a string consisting of A and B:

Select a character in a string. If it is A, replace it with BB. If it is B, replace with AA.

Select a substring that is equal to either AAA or BBB, and delete it from the string.

For example, if the first operation is performed on ABA and the first character is selected, the string becomes BBBA.
If the second operation is performed on BBBAAAA and the fourth through sixth characters are selected, the string becomes BBBA.

These operations can be performed any number of times, in any order.

You are given two string S and T, and q queries a_i, b_i, c_i, d_i.
For each query, determine whether S_{a_i} S_{{a_i}+1} ... S_{b_i}, a substring of S, can be made into T_{c_i} T_{{c_i}+1} ... T_{d_i}, a substring of T.

Constraints

1 \leq |S|, |T| \leq 10^5

S and T consist of letters A and B.

1 \leq q \leq 10^5

1 \leq a_i \leq b_i \leq |S|

1 \leq c_i \leq d_i \leq |T|

Input

Input is given from Standard Input in the following format:

S
T
q
a_1 b_1 c_1 d_1
...
a_q b_q c_q d_q

Output

Print q lines. The i-th line should contain the response to the i-th query. If S_{a_i} S_{{a_i}+1} ... S_{b_i} can be made into T_{c_i} T_{{c_i}+1} ... T_{d_i}, print YES. Otherwise, print NO.

Sample Input 1

BBBAAAABA
BBBBA
4
7 9 2 5
7 9 1 4
1 7 2 5
1 7 2 4

Sample Output 1

YES
NO
YES
NO

The first query asks whether the string ABA can be made into BBBA.
As explained in the problem statement, it can be done by the first operation.

The second query asks whether ABA can be made into BBBB, and the fourth query asks whether BBBAAAA can be made into BBB.
Neither is possible.

The third query asks whether the string BBBAAAA can be made into BBBA.
As explained in the problem statement, it can be done by the second operation.

Sample Input 2

AAAAABBBBAAABBBBAAAA
BBBBAAABBBBBBAAAAABB
10
2 15 2 13
2 13 6 16
1 13 2 20
4 20 3 20
1 18 9 19
2 14 1 11
3 20 3 15
6 16 1 17
4 18 8 20
7 20 3 14

Sample Output 2

YES
YES
YES
YES
YES
YES
NO
NO
NO
NO


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

total=0
for i=1,n do
    total=total+a[n+2*i-1]
end
print(total)

Score : 300 points

Problem Statement

There are 3N participants in AtCoder Group Contest.
The strength of the i-th participant is represented by an integer a_i.
They will form N teams, each consisting of three participants.
No participant may belong to multiple teams.

The strength of a team is defined as the second largest strength among its members.
For example, a team of participants of strength 1, 5, 2 has a strength 2, and a team of three participants of strength 3, 2, 3 has a strength 3.

Find the maximum possible sum of the strengths of N teams.

Constraints

1 ≤ N ≤ 10^5

1 ≤ a_i ≤ 10^{9}

a_i are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the answer.

Sample Input 1

2
5 2 8 5 1 5

Sample Output 1

10

The following is one formation of teams that maximizes the sum of the strengths of teams:

Team 1: consists of the first, fourth and fifth participants.

Team 2: consists of the second, third and sixth participants.

Sample Input 2

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 2

10000000000

The sum of the strengths can be quite large.


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

total=0
for i=3*n,1,-2 do
    if i==n then
        print(total)
        return
    end
    total=total+a[i-1]
end


local n, m = io.read("*n", "*n")
local edge = {}
local color = {}
local searched_len = {}
for i = 1, n do
  edge[i] = {}
  color[i] = 0
  searched_len[i] = -1
end
for i = 1, m do
  local a, b = io.read("*n", "*n")
  table.insert(edge[a], b)
  table.insert(edge[b], a)
end
local q = io.read("*n")
local qv, qd, qc = {}, {}, {}
for iq = 1, q do
  qv[iq], qd[iq], qc[iq] = io.read("*n", "*n", "*n")
end
local tv, td, tc = {}, {}, {}
for iq = q, 1, -1 do
  local taskpos = 1
  tv[1], td[1], tc[1] = qv[iq], qd[iq], qc[iq]
  while 0 < taskpos do
    local src, d, c = tv[taskpos], td[taskpos], tc[taskpos]
    taskpos = taskpos - 1
    if searched_len[src] < d then
      searched_len[src] = d
    end
    if color[src] == 0 then
      color[src] = c
    end
    if 0 < d then
      for i = 1, #edge[src] do
        local dst = edge[src][i]
        if searched_len[dst] < d - 1 then
          taskpos = taskpos + 1
          tv[taskpos] = dst
          td[taskpos] = d - 1
          tc[taskpos] = c
        end
      end
    end
  end
end
for i = 1, n do
  print(color[i])
end

Score : 700 points

Problem Statement

Squid loves painting vertices in graphs.

There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges.
Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1.

Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i.

Find the color of each vertex after the Q operations.

Constraints

1 ≤ N,M,Q ≤ 10^5

1 ≤ a_i,b_i,v_i ≤ N

a_i ≠ b_i

0 ≤ d_i ≤ 10

1 ≤ c_i ≤10^5

d_i and c_i are all integers.

There are no self-loops or multiple edges in the given graph.

Partial Score

200 points will be awarded for passing the testset satisfying 1 ≤ N,M,Q ≤ 2{,}000.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_{M} b_{M}
Q
v_1 d_1 c_1
:
v_{Q} d_{Q} c_{Q}

Output

Print the answer in N lines.
In the i-th line, print the color of vertex i after the Q operations.

Sample Input 1

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

Sample Output 1

2
2
2
2
2
1
0

Initially, each vertex is painted in color 0.
In the first operation, vertices 5 and 6 are repainted in color 1.
In the second operation, vertices 1, 2, 3, 4 and 5 are repainted in color 2.

Sample Input 2

14 10
1 4
5 7
7 11
4 10
14 7
14 3
6 14
8 11
5 13
8 3
8
8 6 2
9 7 85
6 9 3
6 7 5
10 3 1
12 9 4
9 6 6
8 2 3

Sample Output 2

1
0
3
1
5
5
3
3
6
1
3
4
5
3

The given graph may not be connected.


local n, m = io.read("*n", "*n")
local edge = {}
local color = {}
local searched_len = {}
for i = 1, n do
  edge[i] = {}
  color[i] = 0
  searched_len[i] = -1
end
for i = 1, m do
  local a, b = io.read("*n", "*n")
  table.insert(edge[a], b)
  table.insert(edge[b], a)
end
local q = io.read("*n")
local query = {}
for iq = 1, q do
  query[iq] = {io.read("*n", "*n", "*n")}
end
for iq = q, 1, -1 do
  local tasks = {{unpack(query[iq])}}
  while 0 < #tasks do
    local src, d, c = unpack(tasks[#tasks])
    table.remove(tasks)
    if color[src] == 0 then
      color[src] = c
    end
    if 0 < d then
      for i = 1, #edge[src] do
        local dst = edge[src][i]
        if searched_len[dst] < d - 1 then
          table.insert(tasks, {dst, d - 1, c})
        end
      end
    end
  end
end
for i = 1, n do
  print(color[i])
end


Score : 100 points

Problem Statement

Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.

In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".

The current time is A o'clock, and a contest will begin in exactly B hours.
When will the contest begin? Answer in 24-hour time.

Constraints

0 \leq A,B \leq 23

A and B are integers.

Input

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

A B

Output

Print the hour of the starting time of the contest in 24-hour time.

Sample Input 1

9 12

Sample Output 1

21

In this input, the current time is 9 o'clock, and 12 hours later it will be 21 o'clock in 24-hour time.

Sample Input 2

19 0

Sample Output 2

19

The contest has just started.

Sample Input 3

23 2

Sample Output 3

1

The contest will begin at 1 o'clock the next day.


local n, m = io.read("*n", "*n")
local a = {}
for i = 1, n do
  a[i] = {io.read("*n", "*n")}
end
local b = {}
for i = 1, m do
  b[i] = {io.read("*n", "*n")}
end
local mab = math.abs
local function solve(i, j)
  return mab(a[i][1] - b[j][1]) + mab(a[i][2] - b[j][2])
end
for i = 1, n do
  local p, v = 1, solve(i, 1)
  for j = 2, m do
    local tv = solve(i, j)
    if tv < v then
      p, v = j, tv
    end
  end
  print(p)
end

Score : 200 points

Problem Statement

There are N students and M checkpoints on the xy-plane.

The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j).

When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.

The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|.

Here, |x| denotes the absolute value of x.

If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.

Which checkpoint will each student go to?

Constraints

1 \leq N,M \leq 50

-10^8 \leq a_i,b_i,c_j,d_j \leq 10^8

All input values are integers.

Input

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

N M
a_1 b_1
:
a_N b_N
c_1 d_1
:
c_M d_M

Output

Print N lines.

The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go.

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

The Manhattan distance between the first student and each checkpoint is:

For checkpoint 1: |2-(-1)|+|0-0|=3

For checkpoint 2: |2-1|+|0-0|=1

The nearest checkpoint is checkpoint 2. Thus, the first line in the output should contain 2.

The Manhattan distance between the second student and each checkpoint is:

For checkpoint 1: |0-(-1)|+|0-0|=1

For checkpoint 2: |0-1|+|0-0|=1

When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain 1.

Sample Input 2

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

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Sample Output 3

5
4
3
2
1


n = io.read("*n")
lim = math.ceil(math.sqrt(n))
for i = lim, 1, -1 do
  if i * i <= n and n % i == 0 then
    z = n // i
    r = 0
    while 0 < z do
      r, z = r + 1, z // 10
    end
    print(r)
    break
  end
end

Score : 300 points

Problem Statement

You are given an integer N.

For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B.

For example, F(3,11) = 2 since 3 has one digit and 11 has two digits.

Find the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Constraints

1 \leq N \leq 10^{10}

N is an integer.

Input

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

N

Output

Print the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Sample Input 1

10000

Sample Output 1

3

F(A,B) has a minimum value of 3 at (A,B)=(100,100).

Sample Input 2

1000003

Sample Output 2

7

There are two pairs (A,B) that satisfy the condition: (1,1000003) and (1000003,1). For these pairs, F(1,1000003)=F(1000003,1)=7.

Sample Input 3

9876543210

Sample Output 3

6


local function lower_bound(ary, x)
  if(x <= ary[1]) then return 1 end
  local num = #ary
  if(ary[num] < x) then return num + 1 end
  local min, max = 1, num
  while(1 < max - min) do
    local mid = (min + max) // 2
    if(ary[mid] < x) then
      min = mid
    else
      max = mid
    end
  end
  return max
end
local function getComb(n, k)
  local ret = 1
  for i = 1, k do
    ret = ret * (n + 1 - i)
    ret = ret // i
  end
  return ret
end
local n, a, b = io.read("*n", "*n", "*n")
local t = {}
for i = 1, n do t[i] = io.read("*n") end
table.sort(t)
local sum = 0
for i = 1, a do
  sum = sum + t[n + 1 - i]
end
print(string.format("%.8f", sum / a))
local minval = t[n + 1 - a]
local minvalcount = 0
local usecount = 0
for i = 1, n do
  if(t[i] == minval) then
    minvalcount = minvalcount + 1
    if(n + 1 - a <= i) then
      usecount = usecount + 1
    end
  end
end
if minval ~= t[n] then
  print(string.format("%d", getComb(minvalcount, usecount)))
else
  local ret = 0
  for i = a, b do
    ret = ret + getComb(minvalcount, i)
  end
  print(string.format("%d",ret))
end

Score : 400 points

Problem Statement

You are given N items.

The value of the i-th item (1 \leq i \leq N) is v_i.

Your have to select at least A and at most B of these items.

Under this condition, find the maximum possible arithmetic mean of the values of selected items.

Additionally, find the number of ways to select items so that the mean of the values of selected items is maximized.

Constraints

1 \leq N \leq 50

1 \leq A,B \leq N

1 \leq v_i \leq 10^{15}

Each v_i is an integer.

Input

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

N A B
v_1
v_2
...
v_N

Output

Print two lines.

The first line should contain the maximum possible arithmetic mean of the values of selected items. The output should be considered correct if the absolute or relative error is at most 10^{-6}.

The second line should contain the number of ways to select items so that the mean of the values of selected items is maximized.

Sample Input 1

5 2 2
1 2 3 4 5

Sample Output 1

4.500000
1

The mean of the values of selected items will be maximized when selecting the fourth and fifth items. Hence, the first line of the output should contain 4.5.

There is no other way to select items so that the mean of the values will be 4.5, and thus the second line of the output should contain 1.

Sample Input 2

4 2 3
10 20 10 10

Sample Output 2

15.000000
3

There can be multiple ways to select items so that the mean of the values will be maximized.

Sample Input 3

5 1 5
1000000000000000 999999999999999 999999999999998 999999999999997 999999999999996

Sample Output 3

1000000000000000.000000
1


a=io.read()
if a=="H H"or a =="B B"then
  print("H")
else
  print("B")
end

Score : 100 points

Problem Statement

Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest.
In this game, an honest player always tells the truth, and an dishonest player always tell lies.
You are given two characters a and b as the input. Each of them is either H or D, and carries the following information:

If a=H, AtCoDeer is honest; if a=D, AtCoDeer is dishonest.
If b=H, AtCoDeer is saying that TopCoDeer is honest; if b=D, AtCoDeer is saying that TopCoDeer is dishonest.

Given this information, determine whether TopCoDeer is honest.

Constraints

a=H or a=D.

b=H or b=D.

Input

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

a b

Output

If TopCoDeer is honest, print H. If he is dishonest, print D.

Sample Input 1

H H

Sample Output 1

H

In this input, AtCoDeer is honest. Hence, as he says, TopCoDeer is honest.

Sample Input 2

D H

Sample Output 2

D

In this input, AtCoDeer is dishonest. Hence, contrary to what he says, TopCoDeer is dishonest.

Sample Input 3

D D

Sample Output 3

H


local x = io.read("n")

local out
for i = 1, x do
	if i*i + i >= 2 * x then
		out = i
		break
	end
end

print(out)

Score : 200 points

Problem Statement

There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0.
During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right.
That is, if his coordinate at time i-1 is x, he can be at coordinate x-i, x or x+i at time i.
The kangaroo's nest is at coordinate X, and he wants to travel to coordinate X as fast as possible.
Find the earliest possible time to reach coordinate X.

Constraints

X is an integer.

1≤X≤10^9

Input

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

X

Output

Print the earliest possible time for the kangaroo to reach coordinate X.

Sample Input 1

6

Sample Output 1

3

The kangaroo can reach his nest at time 3 by jumping to the right three times, which is the earliest possible time.

Sample Input 2

2

Sample Output 2

2

He can reach his nest at time 2 by staying at his position during the first second, and jumping to the right at the next second.

Sample Input 3

11

Sample Output 3

5


local mmi = math.min
local mma = math.max
local n, k = io.read("*n", "*n")
local a = {}
for i = 1, n do
  local at = io.read("*n")
  if at < k then
    table.insert(a, at)
  end
end
n = #a
table.sort(a, function(x, y) return x > y end)
local function solve()
  if n == 0 then return 0 end
  local tail = {}
  for i = 1, n do
    tail[i] = {}
    -- for j = 1, k - 1 do
    --   tail[i][j] = false
    -- end
  end
  tail[n][a[n]] = true
  local curmax = a[n]
  for i = n - 1, 1, -1 do
    for j = 1, curmax do
      if tail[i + 1][j] then
        tail[i][j] = true
        if j + a[i] < k then
          tail[i][j + a[i]] = true
          curmax = mma(curmax, j + a[i])
        end
      end
    end
    tail[i][a[i]] = true
    curmax = mma(curmax, a[i])
  end
  local head = {}
  for i = 1, k - 1 do
    head[i] = false
  end
  local cnt = 0
  curmax = 0
  for i = 1, n - 1 do
    local ai = a[i]
    local need = false
    for j = k - ai, k - 1 do
      for p = 1, j - 1 do
        local q = j - p
        if head[p] and tail[i + 1][q] then
          need = true
          break
        end
      end
      if head[j] or tail[i + 1][j] then
        need = true
      end
      if need then break end
    end
    if not need then cnt = cnt + 1 end
    for j = mmi(curmax, k - 1 - ai), 1, -1 do
      if head[j] then head[j + ai] = true end
    end
    head[ai] = true
    curmax = mmi(curmax + ai, k - 1)
  end
  do -- i == n
    local ai = a[n]
    local need = false
    for j = k - ai, k - 1 do
      if head[j] then
        need = true
        break
      end
    end
    if not need then cnt = cnt + 1 end
  end
  return cnt
end
print(solve())

Score : 600 points

Problem Statement

AtCoDeer the deer has N cards with positive integers written on them. The number on the i-th card (1≤i≤N) is a_i.
Because he loves big numbers, he calls a subset of the cards good when the sum of the numbers written on the cards in the subset, is K or greater.

Then, for each card i, he judges whether it is unnecessary or not, as follows:

If, for any good subset of the cards containing card i, the set that can be obtained by eliminating card i from the subset is also good, card i is unnecessary.

Otherwise, card i is NOT unnecessary.

Find the number of the unnecessary cards. Here, he judges each card independently, and he does not throw away cards that turn out to be unnecessary.

Constraints

All input values are integers.

1≤N≤5000

1≤K≤5000

1≤a_i≤10^9 (1≤i≤N)

Partial Score

300 points will be awarded for passing the test set satisfying N,K≤400.

Input

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

N K
a_1 a_2 ... a_N

Output

Print the number of the unnecessary cards.

Sample Input 1

3 6
1 4 3

Sample Output 1

1

There are two good sets: {2,3} and {1,2,3}.

Card 1 is only contained in {1,2,3}, and this set without card 1, {2,3}, is also good. Thus, card 1 is unnecessary.

For card 2, a good set {2,3} without card 2, {3}, is not good. Thus, card 2 is NOT unnecessary.

Neither is card 3 for a similar reason, hence the answer is 1.

Sample Input 2

5 400
3 1 4 1 5

Sample Output 2

5

In this case, there is no good set. Therefore, all the cards are unnecessary.

Sample Input 3

6 20
10 4 3 10 25 2

Sample Output 3

3


local n,c,k=io.read("*n","*n","*n")
local t={}
for i=1,n do
    t[i]=io.read("*n")
end
table.sort(t)

local bus=0
local capacity=0
local tadius=t[1]+k
for i=1,n do
    if capacity==c or tadius<t[i] then
        bus=bus+1
        tadius=t[i]+k
        capacity=0
    end
    capacity=capacity+1
end
print(bus+1)

Score : 300 points

Problem Statement

Every day, N passengers arrive at Takahashi Airport.
The i-th passenger arrives at time T_i.

Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers.
Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport.
Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane.
For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).

When setting the departure times for buses under this condition, find the minimum required number of buses.
Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.

Constraints

2 \leq N \leq 100000

1 \leq C \leq 10^9

1 \leq K \leq 10^9

1 \leq T_i \leq 10^9

C, K and T_i are integers.

Input

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

N C K
T_1
T_2
:
T_N

Output

Print the minimum required number of buses.

Sample Input 1

5 3 5
1
2
3
6
12

Sample Output 1

3

For example, the following three buses are enough:

A bus departing at time 4.5, that carries the passengers arriving at time 2 and 3.

A bus departing at time 6, that carries the passengers arriving at time 1 and 6.

A bus departing at time 12, that carries the passenger arriving at time 12.

Sample Input 2

6 3 3
7
6
2
8
10
6

Sample Output 2

3


local n, c, k = io.read("*n", "*n", "*n")
local t = {}
for i = 1, n do
  t[i] = io.read("*n")
end
table.sort(t)
local ans = 0
local curnum, curtime = 0, -1000000007
for i = 1, n do
  if curnum == c or curtime + k < t[i] then
    ans = ans + 1
    curnum = 0
    curtime = t[i]
  end
  curnum = curnum + 1
end
print(ans)


Score : 100 points

Problem Statement

Snuke has a favorite restaurant.

The price of any meal served at the restaurant is 800 yen (the currency of Japan), and each time a customer orders 15 meals, the restaurant pays 200 yen back to the customer.

So far, Snuke has ordered N meals at the restaurant.
Let the amount of money Snuke has paid to the restaurant be x yen, and let the amount of money the restaurant has paid back to Snuke be y yen.
Find x-y.

Constraints

1 ≤ N ≤ 100

Input

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

N

Output

Print the answer.

Sample Input 1

20

Sample Output 1

15800

So far, Snuke has paid 16000 yen, and the restaurant has paid back 200 yen. Thus, the answer is 15800.

Sample Input 2

60

Sample Output 2

47200

Snuke has paid 48000 yen for 60 meals, and the restaurant has paid back 800 yen.


function main()
  local n = tonumber(io.read())
  local s = io.read()

  local animals = {{true, true}, {true, false}, {false, true}, {false, false}}
  for i = 1, #animals do
    for j = 3, n do
      if animals[i][j-1] == (string.sub(s, j-1, j-1) == "o") then
        animals[i][j] = animals[i][j-2]
      else
        animals[i][j] = not animals[i][j-2]
      end
    end
    if
      (animals[i][n] == (string.sub(s, n, n) == "o")) == (animals[i][n-1] == animals[i][1])
      and (animals[i][1] == (string.sub(s, 1, 1) == "o")) == (animals[i][n] == animals[i][2])
    then
      local str = ""
      for j = 1, n do
        if animals[i][j] then
          str = str .. "S"
        else
          str = str .. "W"
        end
      end
      print(str)
      return 0
    end
  end

  print(-1)
end

main()

Score : 500 points

Problem Statement

Snuke, who loves animals, built a zoo.

There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle.
The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.

There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.

Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is o, the animal said that the two neighboring animals are of the same species, and if s_i is x, the animal said that the two neighboring animals are of different species.

More formally, a sheep answered o if the two neighboring animals are both sheep or both wolves, and answered x otherwise.
Similarly, a wolf answered x if the two neighboring animals are both sheep or both wolves, and answered o otherwise.

Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print -1.

Constraints

3 ≤ N ≤ 10^{5}

s is a string of length N consisting of o and x.

Input

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

N
s

Output

If there does not exist an valid assignment that is consistent with s, print -1.
Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.

t is a string of length N consisting of S and W.

If t_i is S, it indicates that the animal numbered i is a sheep. If t_i is W, it indicates that the animal numbered i is a wolf.

Sample Input 1

6
ooxoox

Sample Output 1

SSSWWS

For example, if the animals numbered 1, 2, 3, 4, 5 and 6 are respectively a sheep, sheep, sheep, wolf, wolf, and sheep, it is consistent with their responses. Besides, there is another valid assignment of species: a wolf, sheep, wolf, sheep, wolf and wolf.

Let us remind you: if the neiboring animals are of the same species, a sheep answers o and a wolf answers x. If the neiboring animals are of different species, a sheep answers x and a wolf answers o.

Sample Input 2

3
oox

Sample Output 2

-1

Print -1 if there is no valid assignment of species.

Sample Input 3

10
oxooxoxoox

Sample Output 3

SSWWSSSWWS


local n,m=io.read("*n","*n")
if m-2*n>0 then
    print(n+(m-2*n)//4)
else
    print(m//2)
end

Score : 300 points

Problem Statement

Snuke loves puzzles.

Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:

Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces.

Find the maximum number of Scc groups that can be created when Snuke has N S-shaped pieces and M c-shaped pieces.

Constraints

1 ≤ N,M ≤ 10^{12}

Input

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

N M

Output

Print the answer.

Sample Input 1

1 6

Sample Output 1

2

Two Scc groups can be created as follows:

Combine two c-shaped pieces into one S-shaped piece

Create two Scc groups, each from one S-shaped piece and two c-shaped pieces

Sample Input 2

12345 678901

Sample Output 2

175897


-- C
local sub = string.sub
local n = io.read('*n', '*l')
local s = io.read('*l')
ss = {}
for i = 1, n do
	ss[i] = sub(s, i, i)
end
local ret = nil
if ss[1] == 'o' then
	ret = {
		{[1] = 1, [2] = 1, [n] = 1},
		{[1] = 1, [2] = 0, [n] = 0},
		{[1] = 0, [2] = 0, [n] = 1},
		{[1] = 0, [2] = 1, [n] = 0},
	}
else
	ret = {
		{[1] = 1, [2] = 1, [n] = 0},
		{[1] = 1, [2] = 0, [n] = 1},
		{[1] = 0, [2] = 0, [n] = 0},
		{[1] = 0, [2] = 1, [n] = 1},
	}
end
for i = 2, n-2 do
	for j = 1, 4 do
		local ans = ret[j]
		if ss[i] == 'o' then
			if ans[i] == 1 then
				ans[i + 1] = ans[i - 1]
			else
				ans[i + 1] = 1 - ans[i - 1]
			end
		else
			if ans[i] == 1 then
				ans[i + 1] = 1 - ans[i - 1]
			else
				ans[i + 1] = ans[i - 1]
			end
		end
	end
end

local function isOK(a, b, c, ch)
	if ch == "o" then
		if b == 1 then
			return a == c
		else
			return a ~= c
		end
	else
		if b == 1 then
			return a ~= c
		else
			return a == c
		end
	end
end

local sum = 0
local result = nil
for j = 1, 4 do
	local ans = ret[j]
	if isOK(ans[n-2], ans[n-1], ans[n], ss[n-1]) and isOK(ans[n-1], ans[n], ans[1], ss[n]) then
		sum = sum  + 1
		result = ans
		break
	end
end

if sum == 1 then
	for i = 1, n do
		result[i] = result[i] == 1 and "S" or "W"
	end
	print(table.concat(result))
else
	print(-1)
end


local function comp(a, b)
  return a < b
end

local function lower_bound(ary, x)
  local num = #ary
  if num == 0 then return 1 end
  if not comp(ary[1], x) then return 1 end
  if comp(ary[num], x) then return num + 1 end
  local min, max = 1, num
  while 1 < max - min do
    local mid = (min + max) // 2
    if comp(ary[mid], x) then
      min = mid
    else
      max = mid
    end
  end
  return max
end

local n = io.read("*n")
local stage = {1}
local stagenum = {io.read("*n")}
local stagesum = {stagenum[1]}
local stageaddcnt = {1}
for i = 2, n do
  local a = io.read("*n")
  local pos = lower_bound(stagenum, a)
  if #stagenum < pos then
    table.insert(stage, i)
    table.insert(stagenum, a)
    table.insert(stagesum, a)
    table.insert(stageaddcnt, 1)
  else
    stagesum[pos] = stagesum[pos] + a
    stageaddcnt[pos] = stageaddcnt[pos] + 1
  end
end
local ret = {}
for i = 1, n do
  ret[i] = 0
end

for i = #stagesum, 2, -1 do
  local dst_i = stage[i]
  local num = stagenum[i]
  local sum = stagesum[i]
  local addcnt = stageaddcnt[i]
  ret[dst_i] = sum - addcnt * stagenum[i - 1]
  stageaddcnt[i - 1] = stageaddcnt[i - 1] + addcnt
  stagesum[i - 1] = stagesum[i- 1] + stagenum[i - 1] * addcnt
end
ret[1] = stagesum[1]

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

Score : 700 points

Problem Statement

Snuke loves constructing integer sequences.

There are N piles of stones, numbered 1 through N.
The pile numbered i consists of a_i stones.

Snuke will construct an integer sequence s of length Σa_i, as follows:

Among the piles with the largest number of stones remaining, let x be the index of the pile with the smallest index. Append x to the end of s.

Select a pile with one or more stones remaining, and remove a stone from that pile.

If there is a pile with one or more stones remaining, go back to step 1. Otherwise, terminate the process.

We are interested in the lexicographically smallest sequence that can be constructed. For each of the integers 1,2,3,...,N, how many times does it occur in the lexicographically smallest sequence?

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

Print N lines. The i-th line should contain the number of the occurrences of the integer i in the lexicographically smallest sequence that can be constructed.

Sample Input 1

2
1 2

Sample Output 1

2
1

The lexicographically smallest sequence is constructed as follows:

Since the pile with the largest number of stones remaining is pile 2, append 2 to the end of s. Then, remove a stone from pile 2.

Since the piles with the largest number of stones remaining are pile 1 and 2, append 1 to the end of s (we take the smallest index). Then, remove a stone from pile 2.

Since the pile with the largest number of stones remaining is pile 1, append 1 to the end of s. Then, remove a stone from pile 1.

The resulting sequence is (2,1,1). In this sequence, 1 occurs twice, and 2 occurs once.

Sample Input 2

10
1 2 1 3 2 4 2 5 8 1

Sample Output 2

10
7
0
4
0
3
0
2
3
0


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

for i=1,n-m+1 do
    for j=1,n-m+1 do
        local flag=true
        for k=i,i+m-1 do
            if a[k]:sub(j,j+m-1)~=b[k-m+1] then
                flag=false
            end
        end
        if flag then
            print("Yes")
            return
        end
    end
end
print("No")

Score : 200 points

Problem Statement

You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels.

A pixel is the smallest element of an image, and in this problem it is a square of size 1×1.

Also, the given images are binary images, and the color of each pixel is either white or black.

In the input, every pixel is represented by a character: . corresponds to a white pixel, and # corresponds to a black pixel.

The image A is given as N strings A_1,...,A_N.

The j-th character in the string A_i corresponds to the pixel at the i-th row and j-th column of the image A (1≦i,j≦N).

Similarly, the template image B is given as M strings B_1,...,B_M.

The j-th character in the string B_i corresponds to the pixel at the i-th row and j-th column of the template image B (1≦i,j≦M).

Determine whether the template image B is contained in the image A when only parallel shifts can be applied to the images.

Constraints

1≦M≦N≦50

A_i is a string of length N consisting of # and ..

B_i is a string of length M consisting of # and ..

Input

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

N M
A_1
A_2
:
A_N
B_1
B_2
:
B_M

Output

Print Yes if the template image B is contained in the image A. Print No otherwise.

Sample Input 1

3 2
#.#
.#.
#.#
#.
.#

Sample Output 1

Yes

The template image B is identical to the upper-left 2 × 2 subimage and the lower-right 2 × 2 subimage of A. Thus, the output should be Yes.

Sample Input 2

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

Sample Output 2

No

The template image B, composed of a black pixel, is not contained in the image A composed of white pixels.


local n, m = io.read("*n", "*n", "*l")
local a, b = {}, {}
for i = 1, n do
  local s = io.read()
  for j = 1, n do
    table.insert(a, s:sub(j, j))
  end
end
for i = 1, m do
  local s = io.read()
  for j = 1, m do
    table.insert(b, s:sub(j, j))
  end
end

local function check(x, y)
  for i = 1, m do
    for j = 1, m do
      local i_b = (i - 1) * m + j
      local i_a = (x + i - 2) * n + y + j - 1
      if b[i_b] ~= a[i_a] then return false end
    end
  end
  return true
end

local f = false
for i = 1, n + 1 - m do
  for j = 1, n + 1 - m do
    if check(i, j) then f = true break end
  end
  if f then break end
end
print(f and "Yes" or "No")


local n, m = io.read("*n", "*n")
local t = {}
for i = 1, n do t[i] = {} end
for i = 1, m do
  local a, b = io.read("*n", "*n")
  t[a][b], t[b][a] = true, true
end
local mult = 1
for i = 2, n - 1 do
  mult = mult * i
end
local cnt = 0
for i = 0, mult - 1 do
  local rem = {}
  local resarray = {1}
  for j = 2, n do rem[j - 1] = j end
  local it = i

  local tmpmult = mult
  for j = n - 1, 1, -1 do
    local divfactor = tmpmult / j
    local pos = 1 + math.floor(it / divfactor)
    table.insert(resarray, rem[pos])
    table.remove(rem, pos)
    tmpmult = divfactor
    it = it % divfactor
  end
  local isok = true
  for j = 1, n - 1 do
    if(not t[resarray[j]][resarray[j+1]]) then
      isok = false
      break
    end
  end
  if(isok) then cnt = cnt + 1 end
end
print(cnt)

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)

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.