Score : 400 points

Problem Statement

For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}.

Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.

Find the maximum possible value of M_1 + M_2 + \cdots + M_N.

Constraints

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

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible value of M_1 + M_2 + \cdots + M_N.

Sample Input 1

2

Sample Output 1

1

When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 0 = 1.

Sample Input 2

13

Sample Output 2

78

Sample Input 3

1

Sample Output 3

0


local n = io.read("*n")
print(math.floor(n * (n - 1) / 2))

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

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 l = io.read("*l")
l = tonumber(l)
local result = 0
if l == 1 then
  result = 0
elseif l % 2 == 0 then
  result = (l - 1) * (l / 2)
else
  result = (l - 2) * (l / 2) + (l / 2)
end
print(~~(result))


local n = io.read("*n")
local edge = {}
local srccnt = {}
for i = 1, n * n do
  edge[i] = {}
  srccnt[i] = 0
end
local function getindex(a, b)
  if a < b then
    return (a - 1) * n + b
  else
    return (b - 1) * n + a
  end
end
for i = 1, n do
  local prvidx = getindex(i, io.read("*n"))
  for j = 2, n - 1 do
    local nxtidx = getindex(i, io.read("*n"))
    table.insert(edge[prvidx], nxtidx)
    srccnt[nxtidx] = srccnt[nxtidx] + 1
    prvidx = nxtidx
  end
end
local tasks = {}
for i = 1, n * n do
  if 0 < #edge[i] and srccnt[i] == 0 then
    table.insert(tasks, i)
  end
end
local day = 0
local matched = 0
while 0 < #tasks do
  day = day + 1
  local ng = false
  local newtasks = {}
  for i = 1, #tasks do
    local src = tasks[i]
    matched = matched + #edge[src]
    for j = 1, #edge[src] do
      local dst = edge[src][j]
      srccnt[dst] = srccnt[dst] - 1
      if srccnt[dst] == 0 then
        table.insert(newtasks, dst)
      end
    end
    if ng then break end
  end
  if ng then break end
  tasks = newtasks
end
if matched * 2 < n * (n - 1) then
  day = -1
end
print(day)

Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

1 \leq A_{i, j} \leq N

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.


local mod = 1000000007
local mfl = math.floor
local function bmul(x, y)
  local x0, y0 = x % 31623, y % 31623
  local x1, y1 = mfl(x / 31623), mfl(y / 31623)
  return (x1 * y1 * 14122 + (x1 * y0 + x0 * y1) * 31623 + x0 * y0) % mod
end
local n, k = io.read("*n", "*n")
local a = {}
for i = 1, n do a[i] = io.read("*n") end
local sum = 0
local fact1 = bmul(500000004, bmul(k, k - 1))
local fact2 = bmul(500000004, bmul(k, k + 1))
for i = 1, n - 1 do
  for j = i + 1, n do
    if a[i] < a[j] then
      sum = (sum + fact1) % mod
    elseif a[j] < a[i] then
      sum = (sum + fact2) % mod
    end
  end
end
print(sum)

Score : 300 points

Problem Statement

We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.

Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.

Find the inversion number of B, modulo 10^9 + 7.

Here the inversion number of B is defined as the number of ordered pairs of integers (i,~j)~(0 \leq i < j \leq K \times N - 1) such that B_i > B_j.

Constraints

All values in input are integers.

1 \leq N \leq 2000

1 \leq K \leq 10^9

1 \leq A_i \leq 2000

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 ... A_{N - 1}

Output

Print the inversion number of B, modulo 10^9 + 7.

Sample Input 1

2 2
2 1

Sample Output 1

3

In this case, B~=~2,~1,~2,~1. We have:

B_0 > B_1

B_0 > B_3

B_2 > B_3

Thus, the inversion number of B is 3.

Sample Input 2

3 5
1 1 1

Sample Output 2

0

A may contain multiple occurrences of the same number.

Sample Input 3

10 998244353
10 9 8 7 5 6 3 4 2 1

Sample Output 3

185297239

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


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
----
-- returns n! % m
local function modfactorial(n, m)
    local a = 1
    for i=1, n do
        a = a * i % m
    end
    return a
end
----
local MOD = math.floor(10^9) + 7
local N = read.nl()
local S = read.l():totable()

local lcount = 0
local ans = 1

for i=1,2*N do
    local ev = i % 2 == 0 and 1 or 0
    local c = S[i] == 'W' and 0 or 1
    --[[
        ev  c   example     flip    L           R           use
        0   0   i=3,W       Do not  flip        not flip    R
        0   1   i=3,B       Do      flip        not flip    L
        1   0   i=2,W       Do not  not flip    flip        L
        1   1   i=2,B       Do      not flip    flip        R
    ]]
    if ev ~ c == 0 then
        -- R
        if lcount <= 0 then
            print(0)
            return
        end
        ans = ans * lcount % MOD
        lcount = lcount - 1
    else
        -- L
        lcount = lcount + 1
    end
end
if lcount > 0 then
    print(0)
    return
end

ans = ans * modfactorial(N, MOD) % MOD
print(ans)

Score : 500 points

Problem Statement

There are 2N squares arranged from left to right. You are given a string of length 2N representing the color of each of the squares.

The color of the i-th square from the left is black if the i-th character of S is B, and white if that character is W.

You will perform the following operation exactly N times: choose two distinct squares, then invert the colors of these squares and the squares between them. Here, to invert the color of a square is to make it white if it is black, and vice versa.

Throughout this process, you cannot choose the same square twice or more. That is, each square has to be chosen exactly once.

Find the number of ways to make all the squares white at the end of the process, modulo 10^9+7.

Two ways to make the squares white are considered different if and only if there exists i (1 \leq i \leq N) such that the pair of the squares chosen in the i-th operation is different.

Constraints

1 \leq N \leq 10^5

|S| = 2N

Each character of S is B or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of ways to make all the squares white at the end of the process, modulo 10^9+7. If there are no such ways, print 0.

Sample Input 1

2
BWWB

Sample Output 1

4

There are four ways to make all the squares white, as follows:

Choose Squares 1, 3 in the first operation, and choose Squares 2, 4 in the second operation.

Choose Squares 2, 4 in the first operation, and choose Squares 1, 3 in the second operation.

Choose Squares 1, 4 in the first operation, and choose Squares 2, 3 in the second operation.

Choose Squares 2, 3 in the first operation, and choose Squares 1, 4 in the second operation.

Sample Input 2

4
BWBBWWWB

Sample Output 2

288

Sample Input 3

5
WWWWWWWWWW

Sample Output 3

0


-- B
local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, string.sub(k, i, i)) end local r = io.read local u = table.unpack return function() return r(u(a)) end end})
local N = read.n()
local tmp_sum = 0
for i=1,N do
    local a = read.n()
    tmp_sum = tmp_sum + 1.0 / a
end
local ans = 1 / tmp_sum
print(ans)

Score : 200 points

Problem Statement

Given is a sequence of N integers A_1, \ldots, A_N.

Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Constraints

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print a decimal number (or an integer) representing the value of \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
10 30

Sample Output 1

7.5

\frac{1}{\frac{1}{10} + \frac{1}{30}} = \frac{1}{\frac{4}{30}} = \frac{30}{4} = 7.5.

Printing 7.50001, 7.49999, and so on will also be accepted.

Sample Input 2

3
200 200 200

Sample Output 2

66.66666666666667

\frac{1}{\frac{1}{200} + \frac{1}{200} + \frac{1}{200}} = \frac{1}{\frac{3}{200}} = \frac{200}{3} = 66.6666....

Printing 6.66666e+1 and so on will also be accepted.

Sample Input 3

1
1000

Sample Output 3

1000

\frac{1}{\frac{1}{1000}} = 1000.

Printing +1000.0 and so on will also be accepted.


local mfl = math.floor

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 = mfl((min + max) / 2)
    if comp(ary[mid], x) then
      min = mid
    else
      max = mid
    end
  end
  return max
end

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

local s = io.read()
local t = io.read()
local w = {}
for i = 1, 26 do
  w[i] = {}
end
for i = 1, #s do
  local b = s:byte(i) - 96
  table.insert(w[b], i)
end
for i = 1, #t do
  local b = t:byte(i) - 96
  if #w[b] == 0 then print(-1) os.exit() end
end
local loop = 0
local pos = 0
for i = 1, #t do
  local b = t:byte(i) - 96
  local ub = upper_bound(w[b], pos)
  if #w[b] < ub then
    loop = loop + 1
    pos = w[b][1]
  else
    pos = w[b][ub]
  end
end
print(loop * #s + pos)

Score : 500 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.

Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').

Notes

A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest.

Constraints

1 \leq |s| \leq 10^5

1 \leq |t| \leq 10^5

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1.

Sample Input 1

contest
son

Sample Output 1

10

t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition.

On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition.

Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10.

Sample Input 2

contest
programming

Sample Output 2

-1

t = programming is not a substring of s' = contestcontestcontest.... Thus, there is no integer i satisfying the condition.

Sample Input 3

contest
sentence

Sample Output 3

33

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


local S = io.read("*l")
local SS = S .. S
local T = io.read("*l")

local cur = 0
local ans = 0
local find = string.find
local sub = string.sub
for i=1,#T do
    local c = sub(T, i, i)
    local pos = find(SS, c, cur+1)
    if pos then
        local step = pos - cur
        ans = ans + step
        cur = cur + step
        if cur > #S then
            cur = cur - #S
        end
    else
        print("-1")
        return
    end
end
print(ans)


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

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

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

local function str2tbl(s)
    -- limit of #s is approximately 999959
    --local t = {string.byte(s, 1, #s)}
    local t = {}
    local a = string.byte('a')
    local char = string.char
    local sub = string.sub
    local byte = string.byte
    for i=1, #s do
        t[i] = byte(sub(s, i, i), 1, 1) - a + 1
    end
    return t
end

-- E
local S = str2tbl(io.read("*l"))
local T = str2tbl(io.read("*l"))
--dbgpr_t(S)
--dbgpr_t(T)
local function search_s(n, c)
    for i=n,#S do
        if S[i] == c then
            --return i
            return i - n + 1
        end
    end
    return false
end
local lookup = {}
lookup[0] = {}
for c=1,26 do
    lookup[0][c] = search_s(1, c)
end
for i=1,#S do
    lookup[i] = {}
    for c=1,26 do
        if c == S[i] then
            lookup[i][c] = search_s(i+1, c)
        else
            local prev = lookup[i-1][c]
            lookup[i][c] = prev and prev - 1 or false
        end
    end
end

if DBG then
    for i=0,#S do
        local tbl = lookup[i]
        dbgpr(tbl)
        dbgpr(i)
        io.write("[dbg]")
        for j,v in ipairs(tbl) do
            io.write(string.char(j+96))
            io.write(":")
            io.write(v and v or '*')
            io.write(" ")
        end
        print("")
    end
end
local cur = 0
local ans = 0
local i = 1
while i <= #T do
    local c = T[i]
    dbgpr("!", "i=", i, ans, "c=", c, "cur=", cur, "#lookup", #lookup)
    local step = lookup[cur][c]
    dbgpr(i, ans, c, cur, step)
    if step then
        dbgpr(cur, step)
        ans = ans + step
        cur = cur + step
        assert(cur <= #S)
        i = i + 1
    elseif cur ~= 0 then
        ans = ans + (#S - cur)
        cur = 0
    else
        -- cur == 0
        print("-1")
        return
    end
end
print(ans)


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

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

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

local function str2tbl(s)
    -- limit of #s is approximately 999959
    local t = {string.byte(s, 1, #s)}
    local a = string.byte('a')
    local char = string.char
    for i=1, #t do
        t[i] = t[i] - a + 1
    end
    return t
end

-- E
local S = str2tbl(io.read("*l"))
local T = str2tbl(io.read("*l"))
--dbgpr_t(S)
--dbgpr_t(T)
local function search_s(n, c)
    for i=n,#S do
        if S[i] == c then
            --return i
            return i - n + 1
        end
    end
    return false
end
local lookup = {}
lookup[0] = {}
for c=1,26 do
    lookup[0][c] = search_s(1, c)
end
for i=1,#S do
    lookup[i] = {}
    for c=1,26 do
        if c == S[i] then
            lookup[i][c] = search_s(i+1, c)
        else
            local prev = lookup[i-1][c]
            lookup[i][c] = prev and prev - 1 or false
        end
    end
end

if DBG then
    for i=0,#S do
        local tbl = lookup[i]
        dbgpr(tbl)
        dbgpr(i)
        io.write("[dbg]")
        for j,v in ipairs(tbl) do
            io.write(string.char(j+96))
            io.write(":")
            io.write(v and v or '*')
            io.write(" ")
        end
        print("")
    end
end
local cur = 0
local ans = 0
local i = 1
while i <= #T do
    local c = T[i]
    dbgpr("!", "i=", i, ans, "c=", c, "cur=", cur, "#lookup", #lookup)
    local step = lookup[cur][c]
    dbgpr(i, ans, c, cur, step)
    if step then
        dbgpr(cur, step)
        ans = ans + step
        cur = cur + step
        assert(cur <= #S)
        i = i + 1
    elseif cur ~= 0 then
        ans = ans + (#S - cur)
        cur = 0
    else
        -- cur == 0
        print("-1")
        return
    end
end
print(ans)


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, n do self.stage[stagenum][i] = i end
  for i = n + 1, mul do self.stage[stagenum][i] = emptyvalue end
  self:updateAll()
end
SegTree.getRange = function(self, left, right)
  if left == right then return self.stage[self.stagenum][left] end
  local stagenum = self.stagenum
  local ret = self.emptyvalue
  while left <= right do
    local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    local sz = bls(1, stagenum - stage)
    ret = self.func(ret, self.stage[stage][1 + brs(left - 1, stagenum - stage)])
    left = left + sz
  end
  return ret
end
SegTree.update = function(self, idx)
  for i = self.stagenum - 1, 1, -1 do
    local dst = brs(idx + 1, 1)
    local rem = dst * 4 - 1 - idx
    self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
    idx = dst
  end
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local n = io.read("*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
local b = {}
for i = 1, n do
  b[i] = io.read("*n")
end
local fixedcnt = 0
local fixed = {}
for i = 1, n do
  fixed[i] = a[i] == b[i]
  if fixed[i] then fixedcnt = fixedcnt + 1 end
end
fixed[n + 1] = true

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

local cnt = 0
local st = SegTree.new(n, mergefunc, n + 1)
while true do
  local top = st.stage[1][1]
  if fixed[top] then break end
  local left = top - 1
  if left == 0 then left = n end
  local right = top + 1
  if right == n + 1 then right = 1 end
  local dec = b[left] + b[right]
  local declim1 = mce((b[top] - b[left]) / dec)
  local declim2 = mce((b[top] - b[right]) / dec)
  local declim3 = mce((b[top] - a[top]) / dec)
  local deccnt = mmi(declim1, declim2, declim3)
  deccnt = mma(deccnt, 1)
  b[top] = b[top] - dec * deccnt
  cnt = cnt + deccnt
  if b[top] < a[top] then
    break
  elseif b[top] == a[top] then
    fixed[top] = true
    fixedcnt = fixedcnt + 1
    if fixedcnt == n then break end
  end
  st:update(top)
end
print(fixedcnt == n and cnt or -1)

Score : 800 points

Problem Statement

There are N positive integers arranged in a circle.

Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For this objective, he will repeatedly perform the following operation:

Choose an integer i such that 1 \leq i \leq N.

Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. Replace the i-th number with a+b+c.

Here the 0-th number is the N-th number, and the (N+1)-th number is the 1-st number.

Determine if Takahashi can achieve his objective.
If the answer is yes, find the minimum number of operations required.

Constraints

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

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

Print the minimum number of operations required, or -1 if the objective cannot be achieved.

Sample Input 1

3
1 1 1
13 5 7

Sample Output 1

4

Takahashi can achieve his objective by, for example, performing the following operations:

Replace the second number with 3.

Replace the second number with 5.

Replace the third number with 7.

Replace the first number with 13.

Sample Input 2

4
1 2 3 4
2 3 4 5

Sample Output 2

-1

Sample Input 3

5
5 6 5 2 1
9817 1108 6890 4343 8704

Sample Output 3

25


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, n do self.stage[stagenum][i] = i end
  for i = n + 1, mul do self.stage[stagenum][i] = emptyvalue end
  self:updateAll()
end
SegTree.getRange = function(self, left, right)
  if left == right then return self.stage[self.stagenum][left] end
  local stagenum = self.stagenum
  local ret = self.emptyvalue
  while left <= right do
    local stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    local sz = bls(1, stagenum - stage)
    ret = self.func(ret, self.stage[stage][1 + brs(left - 1, stagenum - stage)])
    left = left + sz
  end
  return ret
end
SegTree.update = function(self, idx)
  for i = self.stagenum - 1, 1, -1 do
    local dst = brs(idx + 1, 1)
    local rem = dst * 4 - 1 - idx
    self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
    idx = dst
  end
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local n = io.read("*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
local b = {}
for i = 1, n do
  b[i] = io.read("*n")
end
local fixedcnt = 0
local fixed = {}
for i = 1, n do
  fixed[i] = a[i] == b[i]
  if fixed[i] then fixedcnt = fixedcnt + 1 end
end
fixed[n + 1] = true

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

local cnt = 0
local st = SegTree.new(n, mergefunc, n + 1)
while true do
  local top = st.stage[1][1]
  if fixed[top] then break end
  local left = top - 1
  if left == 0 then left = n end
  local right = top + 1
  if right == n + 1 then right = 1 end
  b[top] = b[top] - b[left] - b[right]
  cnt = cnt + 1
  if b[top] < a[top] then
    break
  elseif b[top] == a[top] then
    fixed[top] = true
    fixedcnt = fixedcnt + 1
    if fixedcnt == n then break end
  end
  st:update(top)
end
print(fixedcnt == n and cnt or -1)


Score : 100 points

Problem Statement

We have two integers: A and B.

Print the largest number among A + B, A - B, and A \times B.

Constraints

All values in input are integers.

-100 \leq A,\ B \leq 100

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest number among A + B, A - B, and A \times B.

Sample Input 1

-13 3

Sample Output 1

-10

The largest number among A + B = -10, A - B = -16, and A \times B = -39 is -10.

Sample Input 2

1 -33

Sample Output 2

34

The largest number among A + B = -32, A - B = 34, and A \times B = -33 is 34.

Sample Input 3

13 3

Sample Output 3

39

The largest number among A + B = 16, A - B = 10, and A \times B = 39 is 39.


local A, B = io.read("n", "n")
local x, y, z = A+B, A-B, A*B
print(math.max(x,y,z))


local k, x = io.read("*n", "*n")
local t = {}
for i = x - k + 1, x + k - 1 do
  table.insert(t, i)
end
print(table.concat(t, " "))

Score : 200 points

Problem Statement

There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000.

Among them, some K consecutive stones are painted black, and the others are painted white.

Additionally, we know that the stone at coordinate X is painted black.

Print all coordinates that potentially contain a stone painted black, in ascending order.

Constraints

1 \leq K \leq 100

0 \leq X \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K X

Output

Print all coordinates that potentially contain a stone painted black, in ascending order, with spaces in between.

Sample Input 1

3 7

Sample Output 1

5 6 7 8 9

We know that there are three stones painted black, and the stone at coordinate 7 is painted black. There are three possible cases:

The three stones painted black are placed at coordinates 5, 6, and 7.

The three stones painted black are placed at coordinates 6, 7, and 8.

The three stones painted black are placed at coordinates 7, 8, and 9.

Thus, five coordinates potentially contain a stone painted black: 5, 6, 7, 8, and 9.

Sample Input 2

4 0

Sample Output 2

-3 -2 -1 0 1 2 3

Negative coordinates can also contain a stone painted black.

Sample Input 3

1 100

Sample Output 3

100


local num = tonumber(io.read())
local input = {}

for i = 1, num do
  local v = table.pack(string.byte(io.read(), 1, 10))
  table.sort(v)
  v = string.char(table.unpack(v))
  if input[v] ~= nil then
    input[v] = input[v] + 1
  else
    input[v] = 1
  end
end

local t = 0
for k, v in pairs(input) do
  t = t + v * (v - 1) // 2
end
print(t)

Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


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

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

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

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

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

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

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

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

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

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

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

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

local n, m = io.read("*n", "*n")
local t = {}
for i = 1, m do
  t[i] = {}
end
for i = 1, n do
  local a, b = io.read("*n", "*n")
  a = m + 1 - a
  if 0 < a then
    table.insert(t[a], b)
  end
end
local ret = 0
local avl = AvlTree.new(function(x, y) return x > y end, 1)
for i = m, 1, -1 do
  for j = 1, #t[i] do
    avl:push(t[i][j])
  end
  if not avl:empty() then
    ret = ret + avl:pop()
  end
end
print(ret)

Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


local num, day = string.match(io.read(), "(%d+) (%d+)")
num, day = tonumber(num), tonumber(day)
local input = {}
for i = 1, num do
  local a, b = string.match(io.read(), "(%d+) (%d+)")
  table.insert(input, {
	day = tonumber(a),
    result = tonumber(b)
  })
end

table.sort(input, function (a, b)
    if a.result == b.result then
      return a.day > b.day
    else
      return a.result > b.result
    end
  end)

local sum = 0
for i = 1, #input do
  if day >= input[i].day then
    sum = sum + input[i].result
    day = day - 1
  end
  if day <= 0 then
    break
  end
end
print(sum)


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

Score : 100 points

Problem Statement

We have two bottles for holding water.

Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.

Bottle 2 contains C milliliters of water.

We will transfer water from Bottle 2 to Bottle 1 as much as possible.

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


n=io.read("*n")

function digit(n)
  local dig=1
  local c=n
  while math.floor(c/10)~=0 do
    dig=dig+1
    c=math.floor(c/10)
  end
  return dig
end

ans=0
for i=1,n do
  if digit(i)%2==1 then
    ans=ans+1
  end
end

print(ans)

Score : 200 points

Problem Statement

Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).

Constraints

1 \leq N \leq 10^5

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of positive integers less than or equal to N that have an odd number of digits.

Sample Input 1

11

Sample Output 1

9

Among the positive integers less than or equal to 11, nine integers have an odd number of digits: 1, 2, \ldots, 9.

Sample Input 2

136

Sample Output 2

46

In addition to 1, 2, \ldots, 9, another 37 integers also have an odd number of digits: 100, 101, \ldots, 136.

Sample Input 3

100000

Sample Output 3

90909


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

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

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

local primes = getprimes(mce(msq(1000000007)))

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

local dvp = getdivisorparts(sum, primes)
local dvs = getdivisorCore(dvp)

for id = #dvs, 1, -1 do
  local dv = dvs[id]
  local plus, minus = {}, {}
  local z = 0
  local c = 0
  for i = 1, n do
    local v = a[i] % dv
    if v <= dv - v then
      table.insert(minus, v)
      z = z - v
    else
      table.insert(plus, dv - v)
      z = z + dv - v
      c = c + dv - v
    end
  end
  if 0 < z then
    table.sort(plus)
    for i = #plus, 1, -1 do
      local v = plus[i]
      z = z - dv
      c = c - v
      if z == 0 then break end
    end
  elseif z < 0 then
    table.sort(minus)
    for i = #minus, 1, -1 do
      local v = minus[i]
      z = z + dv
      c = c + (dv - v)
      if z == 0 then break end
    end
  end
  if c <= k then print(dv) break end
end

Score : 500 points

Problem Statement

We have a sequence of N integers: A_1, A_2, \cdots, A_N.

You can perform the following operation between 0 and K times (inclusive):

Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element.

Compute the maximum possible positive integer that divides every element of A after the operations. Here a positive integer x divides an integer y if and only if there exists an integer z such that y = xz.

Constraints

2 \leq N \leq 500

1 \leq A_i \leq 10^6

0 \leq K \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_{N-1} A_{N}

Output

Print the maximum possible positive integer that divides every element of A after the operations.

Sample Input 1

2 3
8 20

Sample Output 1

7

7 will divide every element of A if, for example, we perform the following operation:

Choose i = 2, j = 1. A becomes (7, 21).

We cannot reach the situation where 8 or greater integer divides every element of A.

Sample Input 2

2 10
3 5

Sample Output 2

8

Consider performing the following five operations:

Choose i = 2, j = 1. A becomes (2, 6).

Choose i = 2, j = 1. A becomes (1, 7).

Choose i = 2, j = 1. A becomes (0, 8).

Choose i = 2, j = 1. A becomes (-1, 9).

Choose i = 1, j = 2. A becomes (0, 8).

Then, 0 = 8 \times 0 and 8 = 8 \times 1, so 8 divides every element of A. We cannot reach the situation where 9 or greater integer divides every element of A.

Sample Input 3

4 5
10 1 2 22

Sample Output 3

7

Sample Input 4

8 7
1 7 5 6 8 2 6 5

Sample Output 4

5


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.addValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = self.stage[self.stagenum][idx] + value
  for i = self.stagenum - 1, 1, -1 do
    local dst = brs(idx + 1, 1)
    local rem = dst * 4 - 1 - idx
    self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
    idx = dst
  end
end
SegTree.new = function(n, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

local mod = 998244353

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 = mfl((min + max) / 2)
    if comp(ary[mid], x) then
      min = mid
    else
      max = mid
    end
  end
  return max
end

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

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

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

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

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

local p2 = {2}
for i = 2, 200010 do p2[i] = badd(p2[i - 1], p2[i - 1]) end
local function getpow2(x)
  if x == 0 then return 1
  else return p2[x] end
end

local n = io.read("*n")
local xs, ys = {}, {}
local idx_by_x = {}
local sorted_x, sorted_y = {}, {}
local ymap = {}
for i = 1, n do
  xs[i], ys[i] = io.read("*n", "*n")
  idx_by_x[i] = i
  sorted_x[i] = xs[i]
  sorted_y[i] = ys[i]
  ymap[ys[i]] = true
end
table.sort(idx_by_x, function(a, b) return xs[a] < xs[b] end)
table.sort(sorted_x)
table.sort(sorted_y)
local y_uniq = {}
for k, _u in pairs(ymap) do
  table.insert(y_uniq, k)
end
table.sort(y_uniq)
local y_uniq_inv = {}
for i = 1, #y_uniq do
  y_uniq_inv[y_uniq[i]] = i
end

local stLeft = SegTree.new(#y_uniq, function(a, b) return a + b end, 0)

-- by x_sorted index
local x_pattern = {}

local x_left_pos = 1
local x_right_pos = 1
for i_x = 1, n do
  local x = sorted_x[i_x]
  if 1 < i_x and sorted_x[i_x - 1] < x then
    for i = x_left_pos, i_x - 1 do
      local y = ys[idx_by_x[i]]
      local yu = y_uniq_inv[y]
      stLeft:addValue(yu, 1)
    end
    x_left_pos = i_x
  end
  while x_right_pos < n and x == sorted_x[x_right_pos + 1] do
    x_right_pos = x_right_pos + 1
  end
  local x_small_count = x_left_pos - 1
  local x_large_count = n - x_right_pos
  local pat_all = bsub(getpow2(n), 1)
  local pat_xsmall = bsub(getpow2(x_small_count), 1)
  local pat_xlarge = bsub(getpow2(x_large_count), 1)

  local src = idx_by_x[i_x]
  local y = ys[src]
  local y_small_count = lower_bound(sorted_y, y) - 1
  local y_large_count = n + 1 - upper_bound(sorted_y, y)
  local pat_ysmall = bsub(getpow2(y_small_count), 1)
  local pat_ylarge = bsub(getpow2(y_large_count), 1)

  local yu = y_uniq_inv[y]
  local x_small_y_small_count = 0
  if 1 < yu then
    x_small_y_small_count = stLeft:getRange(1, yu - 1)
  end
  local pat_x_small_y_small_count = bsub(getpow2(x_small_y_small_count), 1)
  local x_small_y_large_count = 0
  if yu < #y_uniq then
    x_small_y_large_count = stLeft:getRange(yu + 1, #y_uniq)
  end
  local pat_x_small_y_large_count = bsub(getpow2(x_small_y_large_count), 1)

  local v = badd(pat_all, badd(pat_x_small_y_small_count, pat_x_small_y_large_count))
  v = bsub(v, pat_xsmall)
  v = bsub(v, pat_xlarge)
  v = bsub(v, pat_ysmall)
  v = bsub(v, pat_ylarge)
  x_pattern[i_x] = v
end
x_right_pos = n
local stRight = SegTree.new(#y_uniq, function(a, b) return a + b end, 0)
for i_x = n, 1, -1 do
  local x = sorted_x[i_x]
  if i_x < n and x < sorted_x[i_x + 1] then
    for i = x_right_pos, i_x + 1, -1 do
      local y = ys[idx_by_x[i]]
      local yu = y_uniq_inv[y]
      stRight:addValue(yu, 1)
    end
    x_right_pos = i_x
  end
  local src = idx_by_x[i_x]
  local y = ys[src]
  local yu = y_uniq_inv[y]
  local x_large_y_small_count = 0
  if 1 < yu then
    x_large_y_small_count = stRight:getRange(1, yu - 1)
  end
  local pat_x_large_y_small_count = bsub(getpow2(x_large_y_small_count), 1)
  local x_large_y_large_count = 0
  if yu < #y_uniq then
    x_large_y_large_count = stRight:getRange(yu + 1, #y_uniq)
  end
  local pat_x_large_y_large_count = bsub(getpow2(x_large_y_large_count), 1)
  local v = badd(pat_x_large_y_small_count, pat_x_large_y_large_count)
  x_pattern[i_x] = badd(x_pattern[i_x], v)
end
local ret = 0
for i = 1, n do
  ret = badd(ret, x_pattern[i])
end
print(ret)

Score : 600 points

Problem Statement

We have a set S of N points in a two-dimensional plane. The coordinates of the i-th point are (x_i, y_i). The N points have distinct x-coordinates and distinct y-coordinates.

For a non-empty subset T of S, let f(T) be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate axes, that contains all the points in T. More formally, we define f(T) as follows:

f(T) := (the number of integers i (1 \leq i \leq N) such that a \leq x_i \leq b and c \leq y_i \leq d, where a, b, c, and d are the minimum x-coordinate, the maximum x-coordinate, the minimum y-coordinate, and the maximum y-coordinate of the points in T)

Find the sum of f(T) over all non-empty subset T of S. Since it can be enormous, print the sum modulo 998244353.

Constraints

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

-10^9 \leq x_i, y_i \leq 10^9

x_i \neq x_j (i \neq j)

y_i \neq y_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the sum of f(T) over all non-empty subset T of S, modulo 998244353.

Sample Input 1

3
-1 3
2 1
3 -2

Sample Output 1

13

Let the first, second, and third points be P_1, P_2, and P_3, respectively. S = \{P_1, P_2, P_3\} has seven non-empty subsets, and f has the following values for each of them:

f(\{P_1\}) = 1

f(\{P_2\}) = 1

f(\{P_3\}) = 1

f(\{P_1, P_2\}) = 2

f(\{P_2, P_3\}) = 2

f(\{P_3, P_1\}) = 3

f(\{P_1, P_2, P_3\}) = 3

The sum of these is 13.

Sample Input 2

4
1 4
2 1
3 3
4 2

Sample Output 2

34

Sample Input 3

10
19 -11
-3 -12
5 3
3 -15
8 -14
-9 -20
10 -9
0 2
-7 17
6 -6

Sample Output 3

7222

Be sure to print the sum modulo 998244353.


local A,B=io.read("n","n")
if (A-B)%2==0 then
  print(math.abs(A-B)//2)
else
  print("IMPOSSIBLE")
end

Score: 100 points

Problem Statement

We have two distinct integers A and B.

Print the integer K such that |A - K| = |B - K|.

If such an integer does not exist, print IMPOSSIBLE instead.

Constraints

All values in input are integers.

0 \leq A,\ B \leq 10^9

A and B are distinct.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the integer K satisfying the condition.

If such an integer does not exist, print IMPOSSIBLE instead.

Sample Input 1

2 16

Sample Output 1

9

|2 - 9| = 7 and |16 - 9| = 7, so 9 satisfies the condition.

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394


local a, b = io.read("*n", "*n")
if (math.abs(a - b)) % 2 == 1 then
  print("IMPOSSIBLE")
else
  mid = (a + b) // 2
  print(mid)
end


local N=io.read("n")
local w=0
for i=1,N do
  local p = io.read("n")
  if p~=i then
    w=w+1
  end
end
if w<=2 then
  print("Yes")
else
  print("No")
end

Score : 200 points

Problem Statement

We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.

You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.

Print YES if you can sort p in ascending order in this way, and NO otherwise.

Constraints

All values in input are integers.

2 \leq N \leq 50

p is a permutation of {1,\ 2,\ ...,\ N}.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print YES if you can sort p in ascending order in the way stated in the problem statement, and NO otherwise.

Sample Input 1

5
5 2 3 4 1

Sample Output 1

YES

You can sort p in ascending order by swapping p_1 and p_5.

Sample Input 2

5
2 4 3 5 1

Sample Output 2

NO

In this case, swapping any two elements does not sort p in ascending order.

Sample Input 3

7
1 2 3 4 5 6 7

Sample Output 3

YES

p is already sorted in ascending order, so no operation is needed.


n=io.read("*n")
p={}

for i=1,n do
  table.insert(p, io.read("*n"))
end

c=0
j=0
for i=1,n do
  if p[i]~=j+1 then
    c=c+1
  end
  j=j+1
end

if c<=2 then
  print("YES")
else
  print(c)
  print("NO")
end


n=io.read("*n")
a={}
b={}

for i=1,n+1 do
  table.insert(a,io.read("*n"))
end

for i=1,n do
  table.insert(b,io.read("*n"))
end

ans=0
for i=1,n do
  local s=math.min(a[i], b[i])
  ans=ans+s
  a[i]=a[i]-s
  b[i]=b[i]-s
  local s2=math.min(a[i+1], b[i])
  ans=ans+s2
  a[i+1]=a[i+1]-s2
  b[i]=b[i]-s2
end

print(ans)

Score : 300 points

Problem Statement

There are N+1 towns. The i-th town is being attacked by A_i monsters.

We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3


n=io.read("*n")
a={}
b={}

for i=1,n+1 do
  table.insert(a,io.read("*n"))
end

for i=1,n do
  table.insert(b,io.read("*n"))
end

ans=0
for i=1,n do
  local s=math.min(a[i], b[i])
  ans=ans+s
  a[i]=a[i]-s
  b[i]=b[i]-s
  if b[i]>0 then
    local s2=math.min(a[i+1], b[i])
    ans=ans+s2
    a[i+1]=a[i+1]-s
    b[i]=b[i]-s2
  end
end

print(ans)


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
local function array(dimension, default_val) local n=dimension local m={}if default_val~=nil then m[1]={__index=function()return default_val end}end for i=2,n do m[i]={__index=function(p, k)local c=setmetatable({},m[i-1])rawset(p,k,c)return c end}end return setmetatable({},m[n])end
----
local MOD = math.floor(10^9)+7

local tmp = read.l():totable()
local S = {}
local numflag = false
for i=1,#tmp do
    if tmp[i] == '?' then
        S[i] = '?'
    else
        S[i] = tonumber(tmp[i])
        numflag = true
    end
end
if not numflag then
    print(765928472)
    return
end
local N = #S
local tbl = array(2, 0)
tbl[0][0] = 1
for i=1,N do
    if S[i] == '?' then
        for nd=0,9 do
            for oldm=0,12 do
                local newm = (oldm * 10 + nd) % 13
                tbl[i][newm] = (tbl[i][newm] + tbl[i-1][oldm]) % MOD
            end
        end
    else
        for oldm=0,12 do
            local newm = (oldm * 10 + S[i]) % 13
            tbl[i][newm] = tbl[i-1][oldm]
        end
    end
end
print(tbl[N][5])

Score : 400 points

Problem Statement

Given is a string S. Each character in S is either a digit (0, ..., 9) or ?.

Among the integers obtained by replacing each occurrence of ? with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0.

Since the answer can be enormous, print the count modulo 10^9+7.

Constraints

S is a string consisting of digits (0, ..., 9) and ?.

1 \leq |S| \leq 10^5

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of integers satisfying the condition, modulo 10^9+7.

Sample Input 1

??2??5

Sample Output 1

768

For example, 482305, 002865, and 972665 satisfy the condition.

Sample Input 2

?44

Sample Output 2

1

Only 044 satisfies the condition.

Sample Input 3

7?4

Sample Output 3

0

We may not be able to produce an integer satisfying the condition.

Sample Input 4

?6?42???8??2??06243????9??3???7258??5??7???????774????4?1??17???9?5?70???76???

Sample Output 4

153716888


local s = io.read()
local t = io.read()
local swapped = false
if #s < #t then
  swapped = true
  s, t = t, s
end
local slen = #s
local tlen = #t
s = s .. s

local mma = math.max
local findpos = s:find(t, 1)
local maxlength = 0
while findpos do
  if slen < findpos then
    break
  end
  local curlength = 1
  while true do
    local p = findpos + tlen * curlength
    if p < findpos + slen and t == s:sub(p, p + tlen - 1) then
      curlength = curlength + 1
    else
      break
    end
  end
  maxlength = mma(maxlength, curlength)
  if slen % tlen == 0 and curlength == slen / tlen then
    maxlength = -1
    break
  end
  findpos = s:find(t, findpos + tlen * curlength)
end

local same_s, same_t = true, true
for i = 2, slen do if s:sub(1, 1) ~= s:sub(i, i) then same_s = false break end end
for i = 2, tlen do if t:sub(1, 1) ~= t:sub(i, i) then same_t = false break end end
if same_s and same_t and s:sub(1, 1) == t:sub(1, 1) then
  maxlength = -1
end
if swapped then
  if 0 < maxlength then
    maxlength = 0
  end
end
print(maxlength)

Score : 600 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.

There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.

Notes

A string a is a substring of another string b if and only if there exists an integer x (0 \leq x \leq |b| - |a|) such that, for any y (1 \leq y \leq |a|), a_y = b_{x+y} holds.

We assume that the concatenation of zero copies of any string is the empty string. From the definition above, the empty string is a substring of any string. Thus, for any two strings s and t, i = 0 satisfies the condition in the problem statement.

Constraints

1 \leq |s| \leq 5 \times 10^5

1 \leq |t| \leq 5 \times 10^5

s and t consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print -1.

Sample Input 1

abcabab
ab

Sample Output 1

3

The concatenation of three copies of t, ababab, is a substring of the concatenation of two copies of s, abcabababcabab, so i = 3 satisfies the condition.

On the other hand, the concatenation of four copies of t, abababab, is not a substring of the concatenation of any number of copies of s, so i = 4 does not satisfy the condition.

Similarly, any integer greater than 4 does not satisfy the condition, either. Thus, the number of non-negative integers i satisfying the condition is finite, and the maximum value of such i is 3.

Sample Input 2

aa
aaaaaaa

Sample Output 2

-1

For any non-negative integer i, the concatenation of i copies of t is a substring of the concatenation of 4i copies of s. Thus, there are infinitely many non-negative integers i that satisfy the condition.

Sample Input 3

aba
baaab

Sample Output 3

0

As stated in Notes, i = 0 always satisfies the condition.


local s = io.read()
local t = io.read()
if #s < #t then
  s, t = t, s
end
local slen = #s
local tlen = #t
s = s .. s

local mma = math.max
local findpos = s:find(t, 1)
local maxlength = 0
while findpos do
  if slen < findpos then
    break
  end
  local curlength = 1
  while true do
    local p = findpos + tlen * curlength
    if p < findpos + slen and t == s:sub(p, p + tlen - 1) then
      curlength = curlength + 1
    else
      break
    end
  end
  maxlength = mma(maxlength, curlength)
  if slen % tlen == 0 and curlength == slen / tlen then
    maxlength = -1
    break
  end
  findpos = s:find(t, findpos + tlen * curlength)
end

local same_s, same_t = true, true
for i = 2, slen do if s:sub(1, 1) ~= s:sub(i, i) then same_s = false break end end
for i = 2, tlen do if t:sub(1, 1) ~= t:sub(i, i) then same_t = false break end end
if same_s and same_t and s:sub(1, 1) == t:sub(1, 1) then
  maxlength = -1
end
print(maxlength)


local s = io.read()
local t = io.read()
if #s < #t then
  s, t = t, s
end
local slen = #s
local tlen = #t
s = s .. s

local mma = math.max
local findpos = s:find(t, 1)
local maxlength = 0
while findpos do
  if slen < findpos then
    break
  end
  local curlength = 1
  while true do
    local p = findpos + tlen * curlength
    if p < findpos + slen and t == s:sub(p, p + tlen - 1) then
      curlength = curlength + 1
    else
      break
    end
  end
  maxlength = mma(maxlength, curlength)
  if slen <= curlength * tlen then
    maxlength = -1
    break
  end
  findpos = s:find(t, findpos + tlen)
end
print(maxlength)


local s=io.read("n")
local mod=1000000000
local x=(mod-s%mod)%mod
local y=(s+x)//mod
print(0,0,1000000000,1,x,y)

Score : 400 points

Problem Statement

Given is an integer S.
Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions:

0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9

The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2.

We can prove that there always exist six integers that satisfy the conditions under the constraints of this problem.

Constraints

1 \leq S \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfy the conditions, in this order, with spaces in between.
If multiple solutions exist, any of them will be accepted.

Sample Input 1

3

Sample Output 1

1 0 2 2 0 1

The area of the triangle in a two-dimensional plane whose vertices are (1,0),(2,2), and (0,1) is 3/2.
Printing 3 0 3 1 0 1 or 1 0 0 1 2 2 will also be accepted.

Sample Input 2

100

Sample Output 2

0 0 10 0 0 10

Sample Input 3

311114770564041497

Sample Output 3

314159265 358979323 846264338 327950288 419716939 937510582


local s=io.read("n")
local h=1
local w=s

for i=2,math.sqrt(math.sqrt(s)) do
    if w%i==0 then
        while w%i==0 do
            w=w//i
            h=h*i
        end
    end
end
print(0,0,0,h,w,0)


Score : 100 points

Problem Statement

It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2.

Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r.

Constraints

1 \leq r \leq 100

r is an integer.

Input

Input is given from Standard Input in the following format:

r

Output

Print an integer representing the area of the regular dodecagon.

Sample Input 1

4

Sample Output 1

48

The area of the regular dodecagon is 3 \times 4^2 = 48.

Sample Input 2

15

Sample Output 2

675

Sample Input 3

80

Sample Output 3

19200


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local n, d = io.read("*n", "*n")
print(mce(n / (d * 2 + 1)))

Score : 200 points

Problem Statement

There are N apple trees in a row. People say that one of them will bear golden apples.

We want to deploy some number of inspectors so that each of these trees will be inspected.

Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector deployed under the i-th tree (1 \leq i \leq N) will inspect the trees with numbers between i-D and i+D (inclusive).

Find the minimum number of inspectors that we need to deploy to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq D \leq 20

Input

Input is given from Standard Input in the following format:

N D

Output

Print the minimum number of inspectors that we need to deploy to achieve the objective.

Sample Input 1

6 2

Sample Output 1

2

We can achieve the objective by, for example, placing an inspector under Tree 3 and Tree 4.

Sample Input 2

14 3

Sample Output 2

2

Sample Input 3

20 4

Sample Output 3

3


n = io.read("*n")
t = {}
for i = 1, n do
  t[i] = io.read("*n")
end
local mma = math.max
left = {t[1]}
for i = 2, n do
  left[i] = mma(left[i - 1], t[i])
end
local right = {}
for i = 1, n do right[i] = 0 end
right[n] = t[n]
for i = n - 1, 1, -1 do
  right[i] = mma(right[i + 1], t[i])
end
print(right[2])
if 2 < n then
  for i = 2, n - 1 do
    print(math.max(left[i - 1], right[i + 1]))
  end
  print(left[n - 1])
end

Score : 300 points

Problem Statement

You are given a sequence of length N: A_1, A_2, ..., A_N.
For each integer i between 1 and N (inclusive), answer the following question:

Find the maximum value among the N-1 elements other than A_i in the sequence.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 200000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print N lines. The i-th line (1 \leq i \leq N) should contain the maximum value among the N-1 elements other than A_i in the sequence.

Sample Input 1

3
1
4
3

Sample Output 1

4
3
4

The maximum value among the two elements other than A_1, that is, A_2 = 4 and A_3 = 3, is 4.

The maximum value among the two elements other than A_2, that is, A_1 = 1 and A_3 = 3, is 3.

The maximum value among the two elements other than A_3, that is, A_1 = 1 and A_2 = 4, is 4.

Sample Input 2

2
5
5

Sample Output 2

5
5


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local n = io.read("*n")
local a, b = {}, {}
for i = 1, n do
  a[i] = io.read("*n")
  b[i] = a[i]
end
table.sort(b)
local m1, m2 = b[n], b[n - 1]
for i = 1, n do
  if a[i] == m1 then
    print(m2)
  else
    print(m1)
  end
end


local function lower_bound(key,ary)
    local n=#ary
    if n==0 then
        return 1
    end
    if key<=ary[1] then
        return 1
    end
    if key>ary[n] then
        return n+1
    end
    local min,max=1,n
    while 1<max-min do
        local mid=math.floor((min+max)/2)
        if key>ary[mid] then
            min=mid
        else
            max=mid
        end
    end
    return max
end

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

local INF=math.maxinteger
local LISt={}
for i=1,n do
    LISt[i]=INF
end

local function recLIS(counter)
    local len=0
    for i=1,n do
        if a_map[a[i]]>0 then
            local k=lower_bound(a[i],LISt)
            if LISt[k]<INF then
                a_map[LISt[k]]=a_map[LISt[k]]+1
                LISt[k]=a[i]
                a_map[a[i]]=a_map[a[i]]-1
            else
                LISt[k]=a[i]
                a_map[a[i]]=a_map[a[i]]-1
            end
            len=math.max(k,len)
        end
    end
    n=n-len
    return n==0 and counter+1 or recLIS(counter+1)
end

print(recLIS(0))

Score : 500 points

Problem Statement

You are given a sequence with N integers: A = \{ A_1, A_2, \cdots, A_N \}.
For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied:

If A_i and A_j (i < j) are painted with the same color, A_i < A_j.

Find the minimum number of colors required to satisfy the condition.

Constraints

1 \leq N \leq 10^5

0 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the minimum number of colors required to satisfy the condition.

Sample Input 1

5
2
1
4
5
3

Sample Output 1

2

We can satisfy the condition with two colors by, for example, painting 2 and 3 red and painting 1, 4, and 5 blue.

Sample Input 2

4
0
0
0
0

Sample Output 2

4

We have to paint all the integers with distinct colors.


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local function upper_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 n = io.read("*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
  a[i] = -a[i]
end
local t = {a[1]}
for i = 2, n do
  local pos = upper_bound(t, a[i])
  if i - 1 < pos then
    table.insert(t, a[i])
  else
    t[pos] = a[i]
  end
end
print(#t)


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

if a[0]==n then
    print("Yes")
elseif a[0]==n//3 and #a==2 then
    print("Yes")
elseif #a==3 then
    local b={}
    local thirds=true
    for hat,number in pairs(a) do
        if number~=n//3 then
            thirds=false
        end
        table.insert(b,hat)
    end
    if b[1]~b[2]~b[3]==0 then
        print("Yes")
    else
        print("No")
    end
else
    print("No")
end

Score : 300 points

Problem Statement

Snuke has N hats. The i-th hat has an integer a_i written on it.

There are N camels standing in a circle.
Snuke will put one of his hats on each of these camels.

If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print Yes; otherwise, print No.

The bitwise XOR of the numbers written on the hats on both adjacent camels is equal to the number on the hat on itself.

What is XOR?

The bitwise XOR x_1 \oplus x_2 \oplus \ldots \oplus x_n of n non-negative integers x_1, x_2, \ldots, x_n is defined as follows:

- When x_1 \oplus x_2 \oplus \ldots \oplus x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3 \oplus 5 = 6.

Constraints

All values in input are integers.

3 \leq N \leq 10^{5}

0 \leq a_i \leq 10^{9}

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_{N}

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

Yes

If we put the hats with 1, 2, and 3 in this order, clockwise, the condition will be satisfied for every camel, so the answer is Yes.

Sample Input 2

4
1 2 4 8

Sample Output 2

No

There is no such way to distribute the hats; the answer is No.


mfl, mce = math.floor, math.ceil
mmi, mma = math.min, math.max
bls, brs = bit.lshift, bit.rshift
SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    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
  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
    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 = {}
  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, n do self.stage[stagenum][i] = i end
  for i = n + 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
  stagenum = self.stagenum
  ret = self.emptyvalue
  while left <= right do
    stage = mma(self.left_stage[left], self.sz_stage[right - left + 1])
    sz = bls(1, stagenum - stage)
    ret = self.func(ret, self.stage[stage][1 + brs(left - 1, stagenum - stage)])
    left = left + sz
  end
  return ret
end
SegTree.update = function(self, idx, value)
  for i = self.stagenum - 1, 1, -1 do
    dst = brs(idx + 1, 1)
    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, emptyvalue)
  obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(n, func, emptyvalue)
  return obj
end

n, m = io.read("*n", "*n")
edge = {}
edgenum = {}
offset = {}
for i = 1, n do
  edge[i] = {}
  edgenum[i] = 0
  offset[i] = 0
end
inf = 1000000007
edgenum[n + 1] = inf
for i = 1, m do
  a, b = io.read("*n", "*n")
  edge[a][b], edge[b][a] = true, true
  edgenum[a] = edgenum[a] + 1
  edgenum[b] = edgenum[b] + 1
end
if m % 2 == 1 then
  print(-1)
  os.exit()
end
st = SegTree.new(n, function(a, b) return edgenum[a] < edgenum[b] and a or b end, n + 1)
for i = 1, n do
  src = st.stage[1][1]
  dsts = {}
  for dst, _u in pairs(edge[src]) do
    table.insert(dsts, dst)
  end
  if offset[src] == 1 then
    dst = dsts[#dsts]
    print(src .. " " .. dst)
    edgenum[dst] = edgenum[dst] - 1
    edge[dst][src] = nil
    st:update(dst)
    table.remove(dsts)
  end
  lim = mfl(#dsts / 2)
  for j = 1, lim * 2 do
    dst = dsts[j]
    print(src .. " " .. dst)
    edge[dst][src] = nil
    edgenum[dst] = edgenum[dst] - 1
    st:update(dst)
  end
  if #dsts % 2 == 1 then
    dst = dsts[#dsts]
    print(dst .. " " .. src)
    offset[dst] = (offset[dst] + 1) % 2
    edge[dst][src] = nil
    edgenum[dst] = edgenum[dst] - 1
    st:update(dst)
  end
  edgenum[src] = inf
  st:update(src)
end

Score : 700 points

Problem Statement

You are given a simple connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge connects Vertex A_i and Vertex B_i.
Takahashi will assign one of the two possible directions to each of the edges in the graph to make a directed graph.
Determine if it is possible to make a directed graph with an even number of edges going out from every vertex. If the answer is yes, construct one such graph.

Notes

An undirected graph is said to be simple when it contains no self-loops or multiple edges.

Constraints

2 \leq N \leq 10^5

N-1 \leq M \leq 10^5

1 \leq A_i,B_i \leq N (1\leq i\leq M)

The given graph is simple and connected.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If it is impossible to assign directions to satisfy the requirement, print -1.
Otherwise, print an assignment of directions that satisfies the requirement, in the following format:

C_1 D_1
:
C_M D_M

Here each pair (C_i, D_i) means that there is an edge directed from Vertex C_i to Vertex D_i. The edges may be printed in any order.

Sample Input 1

4 4
1 2
2 3
3 4
4 1

Sample Output 1

1 2
1 4
3 2
3 4

After this assignment of directions, Vertex 1 and 3 will each have two outgoing edges, and Vertex 2 and 4 will each have zero outgoing edges.

Sample Input 2

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

Sample Output 2

-1


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local n = io.read("*n")
local a, b = io.read("*n", "*n")
print(mmi(n * a, b))

Score : 100 points

Problem Statement

N of us are going on a trip, by train or taxi.

The train will cost each of us A yen (the currency of Japan).

The taxi will cost us a total of B yen.

How much is our minimum total travel expense?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq A \leq 50

1 \leq B \leq 50

Input

Input is given from Standard Input in the following format:

N A B

Output

Print an integer representing the minimum total travel expense.

Sample Input 1

4 2 9

Sample Output 1

8

The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen.

Sample Input 2

4 2 7

Sample Output 2

7

Sample Input 3

4 2 8

Sample Output 3

8


local function dist(p1,p2)
  local d=0
  for i=1,#p1 do
    d=d+(p1[i]-p2[i])*(p1[i]-p2[i])
  end
  return math.sqrt(d)
end

local nd={}
for s in io.read():gmatch("%d+") do
  nd[#nd+1]=tonumber(s)
end
local N,D=unpack(nd)

local X={}
for i=1,N do
  X[i]={}
  for s in io.read():gmatch("%d+") do
    X[i][#X[i]+1]=tonumber(s)
  end
end

local count=0
for i=1,N-1 do
  for j=i+1,N do
    local d=dist(X[i],X[j])
    if(d==math.floor(d))then count=count+1 end
  end
end

print(count)

Score : 200 points

Problem Statement

There are N points in a D-dimensional space.

The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).

The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.

How many pairs (i, j) (i < j) are there such that the distance between the i-th point and the j-th point is an integer?

Constraints

All values in input are integers.

2 \leq N \leq 10

1 \leq D \leq 10

-20 \leq X_{ij} \leq 20

No two given points have the same coordinates. That is, if i \neq j, there exists k such that X_{ik} \neq X_{jk}.

Input

Input is given from Standard Input in the following format:

N D
X_{11} X_{12} ... X_{1D}
X_{21} X_{22} ... X_{2D}
\vdots
X_{N1} X_{N2} ... X_{ND}

Output

Print the number of pairs (i, j) (i < j) such that the distance between the i-th point and the j-th point is an integer.

Sample Input 1

3 2
1 2
5 5
-2 8

Sample Output 1

1

The number of pairs with an integer distance is one, as follows:

The distance between the first point and the second point is \sqrt{|1-5|^2 + |2-5|^2} = 5, which is an integer.

The distance between the second point and the third point is \sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}, which is not an integer.

The distance between the third point and the first point is \sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}, which is not an integer.

Sample Input 2

3 4
-3 7 8 2
-12 1 10 2
-2 8 9 3

Sample Output 2

2

Sample Input 3

5 1
1
2
3
4
5

Sample Output 3

10


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

local x={suma}
for i=1,n-1 do
    x[i+1]=2*a[i]-x[i]
end
print(table.concat(x," "))

Score : 400 points

Problem Statement

There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number.

Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1).

When Mountain i (1 \leq i \leq N) receives 2x liters of rain, Dam i-1 and Dam i each accumulates x liters of water (Dam 0 is Dam N).

One day, each of the mountains received a non-negative even number of liters of rain.

As a result, Dam i (1 \leq i \leq N) accumulated a total of A_i liters of water.

Find the amount of rain each of the mountains received. We can prove that the solution is unique under the constraints of this problem.

Constraints

All values in input are integers.

3 \leq N \leq 10^5-1

N is an odd number.

0 \leq A_i \leq 10^9

The situation represented by input can occur when each of the mountains receives a non-negative even number of liters of rain.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N integers representing the number of liters of rain Mountain 1, Mountain 2, ..., Mountain N received, in this order.

Sample Input 1

3
2 2 4

Sample Output 1

4 0 4

If we assume Mountain 1, 2, and 3 received 4, 0, and 4 liters of rain, respectively, it is consistent with this input, as follows:

Dam 1 should have accumulated \frac{4}{2} + \frac{0}{2} = 2 liters of water.

Dam 2 should have accumulated \frac{0}{2} + \frac{4}{2} = 2 liters of water.

Dam 3 should have accumulated \frac{4}{2} + \frac{4}{2} = 4 liters of water.

Sample Input 2

5
3 8 7 5 5

Sample Output 2

2 4 12 2 8

Sample Input 3

3
1000000000 1000000000 0

Sample Output 3

0 2000000000 0


local tonumber=function(...)
  local t={...}
  for i=1,#t do
    t[i]=_G.tonumber(t[i])
  end
  return unpack(t)
end

local N=tonumber(io.read())
local A=setmetatable(
  {tonumber(io.read():gmatch("(%d+)"..string.rep("%s+(%d+)",N-1))())},
  {__index=function(o,k) return o[(k-1)%#o+1] end}
)

local S=0
for i=1,N do
  S=S+A[i]
end

local Y={}
for i=1,N do
  local y=S
  for j=1,N-1,2 do
    y=y-A[i+j]*2
  end
  Y[i]=y
end

print(unpack(Y))


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

local n, q = io.read("*n", "*n")
local edge = {}
local asked = {}
local depth = {}
local childstep = {}
local segpos = {}
for i = 1, n do
  edge[i] = {}
  asked[i] = false
  depth[i] = 0
  childstep[i] = 0
  segpos[i] = 0
end
depth[n + 1] = n + 1
local color = {}
local value = {}
for i = 1, 2 * n - 1 do
  color[i] = 0
  value[i] = 0
end
local colormap = {}
for i = 1, n - 1 do
  local x, y, c, d = io.read("*n", "*n", "*n", "*n")
  table.insert(edge[x], {y, c, d})
  table.insert(edge[y], {x, c, d})
  colormap[i] = {}
end

local stDepth = SegTree.new(2 * n - 1, function(x, y) return depth[x] < depth[y] and x or y end, n + 1)
local stLen = SegTree.new(2 * n - 1, function(x, y) return x + y end, 0)
local tasks = {{1, 0, 0}}
local done = 0
while done < 2 * n - 1 do
  done = done + 1
  local src, sval, scol = tasks[#tasks][1], tasks[#tasks][2], tasks[#tasks][3]
  table.remove(tasks)
  asked[src] = true
  stDepth:setValue(done, src, true)
  stLen:setValue(done, sval, true)
  segpos[src] = done
  if 1 < done then table.insert(colormap[scol], done) end
  local cs = childstep[src]
  while cs < #edge[src] do
    cs = cs + 1
    childstep[src] = cs
    local dst = edge[src][cs][1]
    if not asked[dst] then
      depth[dst] = depth[src] + 1
      table.insert(tasks, {src, edge[src][cs][3], edge[src][cs][2]})
      table.insert(tasks, {dst, -edge[src][cs][3], edge[src][cs][2]})
      break
    end
  end
end
stDepth:updateAll()
stLen:updateAll()
local qlist = {}
for i = 1, q do
  qlist[i] = {i, io.read("*n", "*n", "*n", "*n")}
end
table.sort(qlist, function(x, y) return x[2] < y[2] end)
local curcol = 0
local storeval = {}
for i = 1, q do
  local tmp = qlist[i]
  local ccol, cval, u, v = tmp[2], tmp[3], tmp[4], tmp[5]
  if curcol ~= ccol then
    -- restore
    for j = 1, #storeval do
      stLen:setValue(storeval[j][1], storeval[j][2])
    end
    -- changecolor
    local cmap = colormap[ccol]
    storeval = {}
    for j = 1, #cmap do
      storeval[j] = {cmap[j], stLen:getValue(cmap[j])}
      if storeval[j][2] < 0 then
        stLen:setValue(cmap[j], -cval)
      else
        stLen:setValue(cmap[j], cval)
      end
    end
    curcol = ccol
  end
  -- get parent
  local spu, spv = segpos[u], segpos[v]
  if spv < spu then spu, spv = spv, spu end
  local spp = stDepth:getRange(spu, spv)
  local ret = 0
  if spv < spp then
    ret = ret + mab(stLen:getRange(spv + 1, spp))
  elseif spp < spv then
    ret = ret + mab(stLen:getRange(spp + 1, spv))
  end
  if spu < spp then
    ret = ret + mab(stLen:getRange(spu + 1, spp))
  elseif spp < spu then
    ret = ret + mab(stLen:getRange(spp + 1, spu))
  end
  qlist[i][6] = ret
end

table.sort(qlist, function(x, y) return x[1] < y[1] end)
for i = 1, q do
  print(qlist[i][6])
end

Score : 600 points

Problem Statement

There is a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively.
Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors.

Answer the following Q queries:

Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.)

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

1 \leq a_i, b_i \leq N

1 \leq c_i \leq N-1

1 \leq d_i \leq 10^4

1 \leq x_j \leq N-1

1 \leq y_j \leq 10^4

1 \leq u_j < v_j \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1 c_1 d_1
:
a_{N-1} b_{N-1} c_{N-1} d_{N-1}
x_1 y_1 u_1 v_1
:
x_Q y_Q u_Q v_Q

Output

Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j.

Sample Input 1

5 3
1 2 1 10
1 3 2 20
2 4 4 30
5 2 1 40
1 100 1 4
1 100 1 5
3 1000 3 4

Sample Output 1

130
200
60

The graph in this input is as follows:

Here the edges of Color 1 are shown as solid red lines, the edge of Color 2 is shown as a bold green line, and the edge of Color 4 is shown as a blue dashed line.

Query 1: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 4 is 100 + 30 = 130.

Query 2: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 5 is 100 + 100 = 200.

Query 3: Assuming that the length of every edge whose color is 3 is changed to 1000 (there is no such edge), the distance between Vertex 3 and Vertex 4 is 20 + 10 + 30 = 60. Note that the edges of Color 1 now have their original lengths.


local s = io.read("l")
local t = {}
for i=1,4 do
    local x = string.sub(s, i, i)
    t[x] = (t[x] or 0) + 1
end
for k,v in pairs(t) do
    if v ~= 2 then
        print("No")
        return
    end
end
print("Yes")

Score : 100 points

Problem Statement

You are given a 4-character string S consisting of uppercase English letters.
Determine if S consists of exactly two kinds of characters which both appear twice in S.

Constraints

The length of S is 4.

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No.

Sample Input 1

ASSA

Sample Output 1

Yes

S consists of A and S which both appear twice in S.

Sample Input 2

STOP

Sample Output 2

No

Sample Input 3

FFEE

Sample Output 3

Yes

Sample Input 4

FREE

Sample Output 4

No


local n = io.read("n")
local prev = io.read("n") -- 1
local cur = io.read("n") -- 2
local count = 0
for i=3,n do
    local next = io.read("n")
    if (prev < cur and cur < next) or (next < cur and cur < prev) then
        count = count + 1
    end
    prev = cur
    cur = next
end
print(count)

Score : 200 points

Problem Statement

We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.

Print the number of elements p_i (1 < i < n) that satisfy the following condition:

p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

Constraints

All values in input are integers.

3 \leq n \leq 20

p is a permutation of {1,\ 2,\ ...,\ n}.

Input

Input is given from Standard Input in the following format:

n
p_1 p_2 ... p_n

Output

Print the number of elements p_i (1 < i < n) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5


local n = io.read("*n")
local d = {}
for i = 1, n do d[i] = io.read("*n") end
table.sort(d)
local hn = n // 2
print(d[hn + 1] - d[hn])

Score : 300 points

Problem Statement

Takahashi made N problems for competitive programming.
The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).

He is dividing the problems into two categories by choosing an integer K, as follows:

A problem with difficulty K or higher will be for ARCs.

A problem with difficulty lower than K will be for ABCs.

How many choices of the integer K make the number of problems for ARCs and the number of problems for ABCs the same?

Problem Statement

2 \leq N \leq 10^5

N is an even number.

1 \leq d_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the number of choices of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 1

6
9 1 4 4 6 7

Sample Output 1

2

If we choose K=5 or 6, Problem 1, 5, and 6 will be for ARCs, Problem 2, 3, and 4 will be for ABCs, and the objective is achieved.
Thus, the answer is 2.

Sample Input 2

8
9 1 14 5 5 4 4 14

Sample Output 2

0

There may be no choice of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 3

14
99592 10342 29105 78532 83018 11639 92015 77204 30914 21912 34519 80835 100000 1

Sample Output 3

42685


local mod = 1000000007
local mfl = math.floor

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

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

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

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

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

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

local n, k = io.read("*n", "*n")
local red = n - k
for i = 1, k do
  local blue_cnt = getComb(k - 1, i - 1)
  local red_1 = getComb(red - 1, i - 1)
  local red_2 = getComb(red - 1, i)
  local red_3 = 0
  if i ~= 1 then
    red_3 = getComb(red - 1, i - 2)
  end
  local sum = bmul(blue_cnt, (red_1 * 2 + red_2 + red_3) % mod)
  print(sum)
end

Score : 400 points

Problem Statement

There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.

First, Snuke will arrange the N balls in a row from left to right.

Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.

How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

Constraints

1 \leq K \leq N \leq 2000

Input

Input is given from Standard Input in the following format:

N K

Output

Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

Sample Input 1

5 3

Sample Output 1

3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).

There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).

There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

Sample Input 2

2000 3

Sample Output 2

1998
3990006
327341989

Be sure to print the numbers of arrangements modulo 10^9+7.


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

local mfl, msq = math.floor, math.sqrt
local function solve(n, k)
  local sq = 1 + mfl(msq(n))
  if n < sq * sq then sq = sq - 1 end
  local stage = {}
  for i = 1, sq do
    stage[i] = 1
  end
  local sum = sq
  if sq * (sq + 1) <= n then
    table.insert(stage, mfl(n / sq) - sum)
    sum = sum + stage[sq + 1]
  end
  for i = sq - 1, 1, -1 do
    table.insert(stage, mfl(n / i) - sum)
    sum = sum + stage[#stage]
  end
  local dp1, dp2 = {}, {}
  for i = 1, #stage do
    dp1[i] = stage[i]
  end
  for ik = 2, k do
    local src = ik % 2 == 0 and dp1 or dp2
    local dst = ik % 2 == 0 and dp2 or dp1
    local tsum = 0
    for i = #stage, 1, -1 do
      tsum = badd(tsum, src[#stage - i + 1])
      dst[i] = bmul(stage[i], tsum)
    end
  end
    local ret = 0
  if k % 2 == 0 then
    for i = 1, #stage do
      ret = badd(ret, dp2[i])
    end
  else
    for i = 1, #stage do
      ret = badd(ret, dp1[i])
    end
  end
  return ret
end

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

Score : 600 points

Problem Statement

Find the number of sequences of length K consisting of positive integers such that the product of any two adjacent elements is at most N, modulo 10^9+7.

Constraints

1\leq N\leq 10^9

1 2\leq K\leq 100 (fixed at 21:33 JST)

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of sequences, modulo 10^9+7.

Sample Input 1

3 2

Sample Output 1

5

(1,1), (1,2), (1,3), (2,1), and (3,1) satisfy the condition.

Sample Input 2

10 3

Sample Output 2

147

Sample Input 3

314159265 35

Sample Output 3

457397712