local bls, brs = bit.lshift, bit.rshift
local mmi, mma = math.min, math.max
local n = io.read("*n")
local v, w = {}, {}
for i = 1, n do
  v[i], w[i] = io.read("*n", "*n")
end
local head_tbl = {}
local box = {}
local ten5 = 100000
for i = 256, mmi(n, 1023) do
  head_tbl[i - 255] = {}
  local tbl = head_tbl[i - 255]
  for j = 1, ten5 do
    tbl[j] = 0
  end
  local jlim = i < 512 and 511 or 1023
  local klim = i < 512 and 9 or 10
  for j = 1, jlim do
    local tmpi, tmpj = i, j
    local weight, val = 0, 0
    for k = 1, klim do
      if tmpj % 2 == 1 then
        val = val + v[tmpi]
        weight = weight + w[tmpi]
      end
      tmpi = brs(tmpi, 1)
      tmpj = brs(tmpj, 1)
    end
    if weight <= ten5 then
      tbl[weight] = mma(tbl[weight], val)
    end
  end
  for i = 2, ten5 do
    tbl[i] = mma(tbl[i], tbl[i - 1])
  end
end
local function debug(...)
  -- print(...)
end
local function output(z)
  print(z)
end

debug(os.clock(), collectgarbage("count"))
local q = io.read("*n")
for iq = 1, q do
  if iq % 1000 == 0 then
    debug(iq, os.clock())
  end
  local pos, wlim = io.read("*n", "*n")
  local deg = 0
  do
    local tmp = pos
    while 0 < tmp do
      deg, tmp = deg + 1, brs(tmp, 1)
    end
  end
  if pos < 256 then
    local ans = 0
    local tot = bls(1, deg)
    for j = 0, tot - 1 do
      local tmpi, tmpj = pos, j
      local val, weight = 0, 0
      for k = 1, deg do
        if tmpj % 2 == 1 then
          val, weight = val + v[tmpi], weight + w[tmpi]
        end
        tmpi, tmpj = brs(tmpi, 1), brs(tmpj, 1)
      end
      if weight <= wlim then
        ans = mma(ans, val)
      end
    end
    output(ans)
  elseif pos < 1024 then
    output(head_tbl[pos - 255][wlim])
  else
    deg = deg - 10
    local basepos = pos
    for i = 1, deg do
      basepos = brs(basepos, 1)
    end
    local tbl = head_tbl[basepos - 255]
    local ans = tbl[wlim]
    local tot = bls(1, deg)
    local deglim, mul = 1, 2
    for j = 1, tot - 1 do
      local tmpi, tmpj = pos, j
      local val, weight = 0, 0
      if j == mul then
        deglim, mul = deglim + 1, mul * 2
      end
      for k = 1, deglim do
        if tmpj % 2 == 1 then
          val, weight = val + v[tmpi], weight + w[tmpi]
        end
        tmpi, tmpj = brs(tmpi, 1), brs(tmpj, 1)
      end
      if weight == wlim then
        ans = mma(ans, val)
      elseif weight < wlim then
        ans = mma(ans, val + tbl[wlim - weight])
      end
    end
    output(ans)
  end
end
debug(os.clock())

Score : 700 points

Problem Statement

We have a rooted binary tree with N vertices, where the vertices are numbered 1 to N.
Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex \left[ \frac{i}{2} \right].

Each vertex has one item in it. The item in Vertex i has a value of V_i and a weight of W_i.
Now, process the following query Q times:

Given are a vertex v of the tree and a positive integer L.
Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L.
Find the maximum possible total value of the chosen items.

Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k (k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i.

Constraints

All values in input are integers.

1 \leq N < 2^{18}

1 \leq Q \leq 10^5

1 \leq V_i \leq 10^5

1 \leq W_i \leq 10^5

For the values v and L given in each query, 1 \leq v \leq N and 1 \leq L \leq 10^5.

Input

Let v_i and L_i be the values v and L given in the i-th query.
Then, Input is given from Standard Input in the following format:

N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q

Output

For each integer i from 1 through Q,
the i-th line should contain the response to the i-th query.

Sample Input 1

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

Sample Output 1

0
3
3

In the first query, we are given only one choice: the item with (V, W)=(1,2). Since L = 1, we cannot actually choose it, so our response should be 0.

In the second query, we are given two choices: the items with (V, W)=(1,2) and (V, W)=(2,3). Since L = 5, we can choose both of them, so our response should be 3.

Sample Input 2

15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227

Sample Output 2

256
255
250
247
255
259
223
253


local function check(x, vec)
  local w = {}
  for i = 1, #vec do
    w[i] = vec[i]
  end
  local isok = true
  for i = 1, 62 do
    local rmpos = 0
    for j = #w, 1, -1 do
      if w[j] % 2 == 1 then
        rmpos = j
        break
      end
    end
    if rmpos == 0 then
      if x % 2 == 1 then
        isok = false
        break
      end
    else
      local v = w[rmpos]
      table.remove(w, rmpos)
      if x % 2 == 1 then
        x = v ~ x
      end
      for j = 1, #w do
        if w[j] % 2 == 1 then
          w[j] = v ~ w[j]
        end
      end
    end
    x = x // 2
    for j = 1, #w do
      w[j] = w[j] // 2
    end
  end
  return isok
end
local q = io.read("*n")
for iq = 1, q do
  local n = io.read("*n", "*l")
  local as = io.read()
  local a = {}
  for ac in as:gmatch("%d+") do
    table.insert(a, tonumber(ac))
  end
  local s = io.read()
  local t = {}
  local valid = true
  for i = n, 1, -1 do
    if s:sub(i, i) == "0" then
      table.insert(t, a[i])
    else
      if not check(a[i], t) then
        valid = false break
      end
    end
  end
  print(valid and 0 or 1)
end

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

Score : 400 points

Problem Statement

There are two persons, numbered 0 and 1, and a variable x whose initial value is 0.
The two persons now play a game.
The game is played in N rounds. The following should be done in the i-th round (1 \leq i \leq N):

Person S_i does one of the following:

Replace x with x \oplus A_i, where \oplus represents bitwise XOR.

Do nothing.

Person 0 aims to have x=0 at the end of the game, while Person 1 aims to have x \neq 0 at the end of the game.

Determine whether x becomes 0 at the end of the game when the two persons play optimally.

Solve T test cases for each input file.

Constraints

1 \leq T \leq 100

1 \leq N \leq 200

1 \leq A_i \leq 10^{18}

S is a string of length N consisting of 0 and 1.

All numbers in input are integers.

Input

Input is given from Standard Input in the following format.
The first line is as follows:

T

Then, T test cases follow.
Each test case is given in the following format:

N
A_1 A_2 \cdots A_N
S

Output

For each test case, print a line containing 0 if x becomes 0 at the end of the game, and 1 otherwise.

Sample Input 1

3
2
1 2
10
2
1 1
10
6
2 3 4 5 6 7
111000

Sample Output 1

1
0
0

In the first test case, if Person 1 replaces x with 0 \oplus 1=1, we surely have x \neq 0 at the end of the game, regardless of the choice of Person 0.

In the second test case, regardless of the choice of Person 1, Person 0 can make x=0 with a suitable choice.

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.


Score : 100 points

Problem Statement

Compute A \times B.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the value A \times B as an integer.

Sample Input 1

2 5

Sample Output 1

10

We have 2 \times 5 = 10.

Sample Input 2

100 100

Sample Output 2

10000


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) assert(type(default_val) ~= 'table') 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 function tostringxx(o, depth) depth = depth or 0 if depth > 10 then return "<too deep!>" end if o == _G then return "<_G>" end local indent0 = (" "):rep((depth) * 2) local indent1 = (" "):rep((depth+1) * 2) local indent2= (" "):rep((depth+2) * 2) if type(o) == 'table' then local keys = {} local types = {} for k in pairs(o) do types[type(k)] = true table.insert(keys, k) end local types_count = 0 local lasttype for k in pairs(types) do types_count = types_count + 1 lasttype = k end if types_count == 1 and (lasttype == 'string' or lasttype == 'number') then table.sort(keys) end local inside = {} for i=1,#keys do local k = keys[i] local v = o[k] if type(k) == 'string' then k = string.format('%q', k) end table.insert(inside, indent1 .. '['..tostring(k)..'] = ' .. tostringxx(v, depth + 1)) end return '{\n' .. table.concat(inside, ',\n') .. '\n' .. indent0 .. '}' else if type(o) == 'string' then o = string.format('%q', o) end return tostring(o) end end
local function richtraceback() local x = 2 while true do local info = debug.getinfo(x) if not info then break end local fname = '<' .. info.short_src .. ":" .. info.linedefined .. ">" if info.name then fname = info.name end print(info.short_src .. ":" .. info.currentline .. ": in " .. ("%q"):format(fname)) print(" LOCALS:") local p = 1 while true do local name, val = debug.getlocal(x,p) if not name then break end print(" " .. name .. ": " .. tostringxx(val, 3)) p = p + 1 end print(" UPVALUES:") for p=1,info.nups do local name, val = debug.getupvalue(info.func,p) if not name then break end print(" " .. name .. ": " .. tostringxx(val, 3)) end x = x + 1 end end
local function myassert(b) if not b then richtraceback() error("assertion failed") end end
----
local function factorize(n)
    local nn = n
    local lst = {}
    for i=2, math.floor(1 + n^0.5) do
        local k = 0
        while nn % i == 0 do
            k = k + 1
            nn = nn // i
        end
        if k > 0 then
            table.insert(lst, {i, k})
        end
    end
    if nn ~= 1 then
        table.insert(lst, {nn, 1})
    end
    return lst
end
----
local N = read.n()
local lst = factorize(N)
local ans = 0
for k,v in ipairs(lst) do
    local p, n = v[1], v[2]
    local cur = n
    for i=1,n do
        if i <= cur then
            ans = ans + 1
            cur = cur - i
        else
            break
        end
    end
end
print(ans)

Score : 400 points

Problem Statement

Given is a positive integer N. Consider repeatedly applying the operation below on N:

First, choose a positive integer z satisfying all of the conditions below:

z can be represented as z=p^e, where p is a prime number and e is a positive integer;

z divides N;

z is different from all integers chosen in previous operations.

Then, replace N with N/z.

Find the maximum number of times the operation can be applied.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum number of times the operation can be applied.

Sample Input 1

24

Sample Output 1

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=12.)

Choose z=3 (=3^1). (Now we have N=4.)

Choose z=4 (=2^2). (Now we have N=1.)

Sample Input 2

1

Sample Output 2

0

We cannot apply the operation at all.

Sample Input 3

64

Sample Output 3

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=32.)

Choose z=4 (=2^2). (Now we have N=8.)

Choose z=8 (=2^3). (Now we have N=1.)

Sample Input 4

1000000007

Sample Output 4

1

We can apply the operation once by, for example, making the following choice:

z=1000000007 (=1000000007^1). (Now we have N=1.)

Sample Input 5

997764507000

Sample Output 5

7


local mfl, mce = math.floor, math.ceil
local n = io.read("*n")
local a, b = {}, {}
for i = 1, n do
  a[i], b[i] = io.read("*n", "*n")
end

local function solvelow(x)
  local c = 0
  for i = 1, n do
    if a[i] <= x then
      c = c + 1
    end
  end
  return n + 1 <= c * 2
end

local function solvehigh(x)
  local c = 0
  for i = 1, n do
    if x <= b[i] then
      c = c + 1
    end
  end
  return n + 1 <= c * 2
end

local function solvelow_even(x)
  local c = 0
  local lowmax, highmin = -1, 2000000007
  for i = 1, n do
    if a[i] <= x then
      c = c + 1
      if lowmax < a[i] then
        lowmax = a[i]
      end
    else
      if a[i] < highmin then
        highmin = a[i]
      end
    end
  end
  if n < c * 2 then return true
  elseif n == c * 2 then
    local diff = x - lowmax
    return highmin - x <= diff
  else
    return false
  end
end

local function solvehigh_even(x)
  local c = 0
  local lowmax, highmin = -1, 2000000007
  for i = 1, n do
    if x <= b[i] then
      c = c + 1
      if b[i] < highmin then
        highmin = b[i]
      end
    else
      if lowmax < b[i] then
        lowmax = b[i]
      end
    end
  end
  if n < c * 2 then return true
  elseif n == c * 2 then
    local diff = highmin - x
    return x - lowmax <= diff
  else
    return false
  end
end

if n % 2 == 1 then
  local min, max = 0, 1000000000
  while 1 < max - min do
    local mid = mfl((min + max) / 2)
    if solvelow(mid) then
      max = mid
    else
      min = mid
    end
  end
  local lowlim = max
  min, max = 1, 1000000001
  while 1 < max - min do
    local mid = mfl((min + max) / 2)
    if solvehigh(mid) then
      min = mid
    else
      max = mid
    end
  end
  local highlim = min
  print(highlim - lowlim + 1)
else
  for i = 1, n do
    a[i], b[i] = a[i] * 2, b[i] * 2
  end
  local min, max = 0, 2000000100
  while 1 < max - min do
    local mid = mfl((min + max) / 2)
    if solvelow_even(mid) then
      max = mid
    else
      min = mid
    end
  end
  local lowlim = max
  min, max = 1, 2000000101
  while 1 < max - min do
    local mid = mfl((min + max) / 2)
    if solvehigh_even(mid) then
      min = mid
    else
      max = mid
    end
  end
  local highlim = min
  print(highlim - lowlim + 1)
end

Score : 500 points

Problem Statement

There are N integers X_1, X_2, \cdots, X_N, and we know that A_i \leq X_i \leq B_i.
Find the number of different values that the median of X_1, X_2, \cdots, X_N can take.

Notes

The median of X_1, X_2, \cdots, X_N is defined as follows. Let x_1, x_2, \cdots, x_N be the result of sorting X_1, X_2, \cdots, X_N in ascending order.

If N is odd, the median is x_{(N+1)/2};

if N is even, the median is (x_{N/2} + x_{N/2+1}) / 2.

Constraints

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

1 \leq A_i \leq 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 B_1
A_2 B_2
:
A_N B_N

Output

Print the answer.

Sample Input 1

2
1 2
2 3

Sample Output 1

3

If X_1 = 1 and X_2 = 2, the median is \frac{3}{2};

if X_1 = 1 and X_2 = 3, the median is 2;

if X_1 = 2 and X_2 = 2, the median is 2;

if X_1 = 2 and X_2 = 3, the median is \frac{5}{2}.

Thus, the median can take three values: \frac{3}{2}, 2, and \frac{5}{2}.

Sample Input 2

3
100 100
10 10000
1 1000000000

Sample Output 2

9991


local mmi, mma = math.min, math.max
local mod = 998244353
local mfl = math.floor
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 n, s = io.read("*n", "*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
local dp = {}
for i = 1, s + 1 do
  dp[i] = 0
end
dp[1] = 1
for i = 1, n do
  local v = a[i]
  for j = s + 1, mma(1, s + 2 - v), -1 do
    dp[j] = bmul(dp[j], 2)
  end
  for j = s + 1 - v, 1, -1 do
    dp[j + v] = badd(dp[j + v], dp[j])
    dp[j] = bmul(dp[j], 2)
  end
end
print(dp[s + 1])

Score : 600 points

Problem Statement

Given are a sequence of N positive integers A_1, A_2, \ldots, A_N and another positive integer S.

For a non-empty subset T of the set \{1, 2, \ldots , N \}, let us define f(T) as follows:

f(T) is the number of different non-empty subsets \{x_1, x_2, \ldots , x_k \} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.

Find the sum of f(T) over all 2^N-1 subsets T of \{1, 2, \ldots , N \}. Since the sum can be enormous, print it modulo 998244353.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq S \leq 3000

1 \leq A_i \leq 3000

Input

Input is given from Standard Input in the following format:

N S
A_1 A_2 ... A_N

Output

Print the sum of f(T) modulo 998244353.

Sample Input 1

3 4
2 2 4

Sample Output 1

6

For each T, the value of f(T) is shown below. The sum of these values is 6.

f(\{1\}) = 0

f(\{2\}) = 0

f(\{3\}) = 1 (One subset \{3\} satisfies the condition.)

f(\{1, 2\}) = 1 (\{1, 2\})

f(\{2, 3\}) = 1 (\{3\})

f(\{1, 3\}) = 1 (\{3\})

f(\{1, 2, 3\}) = 2 (\{1, 2\}, \{3\})

Sample Input 2

5 8
9 9 9 9 9

Sample Output 2

0

Sample Input 3

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

Sample Output 3

3296


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.clear = function(self)
  local n = #self.box
  self.root = 1
  self.box = {}
  for i = n + 1, 2, -1 do self.box[n + 2 - i] = i end
  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 q = io.read("*n")
local len = {}
local function lt(x, y)
  return len[x] < len[y]
end
local avl = AvlTree.new(lt, 1)

local function pushfunc(dst, dstcost)
  if not len[dst] or dstcost < len[dst] then
    len[dst] = dstcost
    avl:push(dst)
  end
end

for iq = 1, q do
  local n, a, b, c, d = io.read("*n", "*n", "*n", "*n", "*n")
  local t = {}
  len = {}
  len[n] = 0
  avl:clear()
  avl:push(n)
  local inf = 1000000007 * 1000000007
  local cand = inf
  while not avl:empty() do
    local src = avl:pop()
    local cost = len[src]
    local zf = d * src
    if zf < 1000000000 * 2 * 128 then
      local z = cost + d * src
      if 1 <= z then
        cand = mmi(cand, z)
      end
    end
    if 1 < src then
      -- print(src, cost)
      local dst = src // 2
      local dstcost = cost + d * (src % 2) + a
      pushfunc(dst, dstcost)
      if dst % 2 ~= 0 then
        dst = dst + 1
        dstcost = cost + d * (2 - (src % 2)) + a
        pushfunc(dst, dstcost)
      end
      dst = src // 3
      dstcost = cost + d * (src % 3) + b
      pushfunc(dst, dstcost)
      if dst % 3 ~= 0 then
        dst = dst + 1
        dstcost = cost + d * (3 - (src % 3)) + b
        pushfunc(dst, dstcost)
      end
      dst = src // 5
      dstcost = cost + d * (src % 5) + c
      pushfunc(dst, dstcost)
      if dst % 5 ~= 0 then
        dst = dst + 1
        dstcost = cost + d * (5 - (src % 5)) + c
        pushfunc(dst, dstcost)
      end
    end
  end
  print(cand)
end

Score : 400 points

Problem Statement

You start with the number 0 and you want to reach the number N.

You can change the number, paying a certain amount of coins, with the following operations:

Multiply the number by 2, paying A coins.

Multiply the number by 3, paying B coins.

Multiply the number by 5, paying C coins.

Increase or decrease the number by 1, paying D coins.

You can perform these operations in arbitrary order and an arbitrary number of times.

What is the minimum number of coins you need to reach N?

You have to solve T testcases.

Constraints

1 \le T \le 10

1 \le N \le 10^{18}

1 \le A, B, C, D \le 10^9

All numbers N, A, B, C, D are integers.

Input

The input is given from Standard Input. The first line of the input is

T

Then, T lines follow describing the T testcases.
Each of the T lines has the format

N A B C D

Output

For each testcase, print the answer on Standard Output followed by a newline.

Sample Input 1

5
11 1 2 4 8
11 1 2 2 8
32 10 8 5 4
29384293847243 454353412 332423423 934923490 1
900000000000000000 332423423 454353412 934923490 987654321

Sample Output 1

20
19
26
3821859835
23441258666

For the first testcase, a sequence of moves that achieves the minimum cost of 20 is:

Initially x = 0.

Pay 8 to increase by 1 (x = 1).

Pay 1 to multiply by 2 (x = 2).

Pay 1 to multiply by 2 (x = 4).

Pay 2 to multiply by 3 (x = 12).

Pay 8 to decrease by 1 (x = 11).

For the second testcase, a sequence of moves that achieves the minimum cost of 19 is:

Initially x = 0.

Pay 8 to increase by 1 (x = 1).

Pay 1 to multiply by 2 (x = 2).

Pay 2 to multiply by 5 (x = 10).

Pay 8 to increase by 1 (x = 11).


local mmi, mma = math.min, math.max
local n = io.read("*n")

local used = {}
local len = {}
local cost = {}
for i = 1, n do
  for j = 1, n do
    local idx = (i - 1) * n + j
    local z = mmi(i - 1, j - 1, n - i, n - j)
    len[idx] = z
    cost[idx] = 1
  end
end

local ret = 0
-- local t = {}
local tasks = {}

for i = 1, n * n do
  -- t[i] = io.read("*n")
  local pos = io.read("*n")
  ret = ret + len[pos]
  cost[pos] = 0

  local done = 0
  local taskpos = 1
  tasks[1] = pos

  local function walk(src, dst)
    if len[src] + cost[src] < len[dst] then
      len[dst] = len[src] + cost[src]
      taskpos = taskpos + 1
      tasks[taskpos] = dst
    end
  end

  while done < taskpos do
    done = done + 1
    local idx = tasks[done]
    if n < idx then walk(idx, idx - n) end
    if idx <= (n - 1) * n then walk(idx, idx + n) end
    if idx % n ~= 0 then walk(idx, idx + 1) end
    if idx % n ~= 1 then walk(idx, idx - 1) end
  end
end
print(ret)

Score : 700 points

Problem Statement

Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by N^2-N+1,\dots, N^2.

At the end of the movie, the viewers go out of the cinema in a certain order: the i-th viewer leaving her seat is the one denoted by the number P_i. The viewer P_{i+1} waits until viewer P_i has left the cinema before leaving her seat.
To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its 4 adjacent seats (same row or same column).
While leaving the cinema, it might be that a certain viewer x goes through a seat currently occupied by viewer y; in that case viewer y will hate viewer x forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.

Compute the number of pairs of viewers (x, y) such that y will hate x forever.

Constraints

2 \le N \le 500

The sequence P_1, P_2, \dots, P_{N^2} is a permutation of \{1, 2, \dots, N^2\}.

Input

The input is given from Standard Input in the format

N
P_1 P_2 \cdots P_{N^2}

Output

If ans is the number of pairs of viewers described in the statement, you should print on Standard Output

ans

Sample Input 1

3
1 3 7 9 5 4 8 6 2

Sample Output 1

1

Before the end of the movie, the viewers are arranged in the cinema as follows:

1 2 3
4 5 6
7 8 9

The first four viewers leaving the cinema (1, 3, 7, 9) can leave the cinema without going through any seat, so they will not be hated by anybody.

Then, viewer 5 must go through one of the seats where viewers 2, 4, 6, 8 are currently seated while leaving the cinema; hence he will be hated by at least one of those viewers.

Finally the remaining viewers can leave the cinema (in the order 4, 8, 6, 2) without going through any occupied seat (actually, they can leave the cinema without going through any seat at all).

Sample Input 2

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

Sample Output 2

3

Sample Input 3

6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30

Sample Output 3

11


n = io.read("*n")
n = n % 10
if n % 10 == 3 then
  print("bon")
elseif n == 0 or n == 1 or n == 6 or n == 8 then
  print("pon")
else
  print("hon")
end

Score: 100 points

Problem Statement

The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.

When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a positive integer N not exceeding 999 is as follows:

hon when the digit in the one's place of N is 2, 4, 5, 7, or 9;

pon when the digit in the one's place of N is 0, 1, 6 or 8;

bon when the digit in the one's place of N is 3.

Given N, print the pronunciation of "本" in the phrase "N 本".

Constraints

N is a positive integer not exceeding 999.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

16

Sample Output 1

pon

The digit in the one's place of 16 is 6, so the "本" in "16 本" is pronounced pon.

Sample Input 2

2

Sample Output 2

hon

Sample Input 3

183

Sample Output 3

bon


K=io.read"*n"
io.read()
S=io.read()
if(#S<=K)then print(S)
else print(S:sub(1,K).."...")end

Score: 200 points

Problem Statement

We have a string S consisting of lowercase English letters.

If the length of S is at most K, print S without change.

If the length of S exceeds K, extract the first K characters in S, append ... to the end of them, and print the result.

Constraints

K is an integer between 1 and 100 (inclusive).

S is a string consisting of lowercase English letters.

The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

K
S

Output

Print a string as stated in Problem Statement.

Sample Input 1

7
nikoandsolstice

Sample Output 1

nikoand...

nikoandsolstice has a length of 15, which exceeds K=7.

We should extract the first 7 characters in this string, append ... to the end of them, and print the result nikoand....

Sample Input 2

40
ferelibenterhominesidquodvoluntcredunt

Sample Output 2

ferelibenterhominesidquodvoluntcredunt

The famous quote from Gaius Julius Caesar.


local a,b,h,m=io.read("n","n","n","n")
local angle=h*(2*math.pi/12)+m*(math.pi/360)-m*(2*math.pi/60)
local dist=math.sqrt(a^2+b^2-2*a*b*math.cos(angle))
print(string.format("%.20f",dist))

Score: 300 points

Problem Statement

Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively.

An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to make one full rotation, respectively.

At 0 o'clock, the two hands overlap each other. H hours and M minutes later, what is the distance in centimeters between the unfixed endpoints of the hands?

Constraints

All values in input are integers.

1 \leq A, B \leq 1000

0 \leq H \leq 11

0 \leq M \leq 59

Input

Input is given from Standard Input in the following format:

A B H M

Output

Print the answer without units. Your output will be accepted when its absolute or relative error from the correct value is at most 10^{-9}.

Sample Input 1

3 4 9 0

Sample Output 1

5.00000000000000000000

The two hands will be in the positions shown in the figure below, so the answer is 5 centimeters.

Sample Input 2

3 4 10 40

Sample Output 2

4.56425719433005567605

The two hands will be in the positions shown in the figure below. Note that each hand always rotates at constant angular velocity.


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

local len = {}
local ret = {}
local inf = 1000000007
for i = 1, n do
  len[i] = inf
  ret[i] = 0
end
len[1] = 0

local tasks = {1}
for i = 1, n do
  local src = tasks[i]
  -- print(src)
  -- print(len[src])
  for dst, _u in pairs(edge[src]) do
    -- print(src .. " to " .. dst)
    if len[dst] + 1 == len[src] then
      ret[src] = dst
    elseif len[dst] == inf then
      len[dst] = len[src] + 1
      -- print("INS", dst)
      table.insert(tasks, dst)
    end
  end
end
print("Yes")
for i = 2, n do
  print(ret[i])
end

Score: 400 points

Problem Statement

There is a cave.

The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.

It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.

Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.

If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.

Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

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

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

A_i \neq B_i\ (1 \leq i \leq M)

One can travel between any two rooms by traversing passages.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If there is no way to place signposts satisfying the objective, print No.

Otherwise, print N lines. The first line should contain Yes, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.

Sample Input 1

4 4
1 2
2 3
3 4
4 2

Sample Output 1

Yes
1
2
2

If we place the signposts as described in the sample output, the following happens:

Starting in Room 2, you will reach Room 1 after traversing one passage: (2) \to 1. This is the minimum number of passages possible.

Starting in Room 3, you will reach Room 1 after traversing two passages: (3) \to 2 \to 1. This is the minimum number of passages possible.

Starting in Room 4, you will reach Room 1 after traversing two passages: (4) \to 2 \to 1. This is the minimum number of passages possible.

Thus, the objective is satisfied.

Sample Input 2

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

Sample Output 2

Yes
6
5
5
1
1

If there are multiple solutions, any of them will be accepted.


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

local counter=1
for i=1,n do
    counter=counter*2%1000000007
end
counter=counter-1

for k,v in pairs(iwashi) do
    if iwashi[k] and iwashi[-k] then
        counter=counter-(iwashi[k]*iwashi[-k]%1000000007)
    end
end
print(counter)

Score: 500 points

Problem Statement

We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively.

We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time.

The i-th and j-th sardines (i \neq j) are on bad terms if and only if A_i \cdot A_j + B_i \cdot B_j = 0.

In how many ways can we choose the set of sardines to put into the cooler? Since the count can be enormous, print it modulo 1000000007.

Constraints

All values in input are integers.

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

-10^{18} \leq A_i, B_i \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the count modulo 1000000007.

Sample Input 1

3
1 2
-1 1
2 -1

Sample Output 1

5

There are five ways to choose the set of sardines, as follows:

The 1-st

The 1-st and 2-nd

The 2-nd

The 2-nd and 3-rd

The 3-rd

Sample Input 2

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

Sample Output 2

479


local mod = 1000000007

local function bmul(x, y)
  return (x * y) % 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 getgcd(x, y)
  while 0 < x do
    x, y = y % x, x
  end
  return y
end

local x1, y1 = {}, {}
local x2, y2 = {}, {}
local xzero = 0
local yzero = 0
local zero = 0

local n = io.read("*n", "*l")
for i = 1, n do
  local a, b = io.read("*n", "*n")
  if a == 0 and b == 0 then
    zero = zero + 1
  elseif a == 0 then
    xzero = xzero + 1
  elseif b == 0 then
    yzero = yzero + 1
  else
    if b < 0 then
      a, b = -a, -b
    end
    if 0 < a then
      local gcd = getgcd(a, b)
      table.insert(x1, a // gcd)
      table.insert(y1, b // gcd)
    else
      local gcd = getgcd(-a, b)
      table.insert(x2, -a // gcd)
      table.insert(y2, b // gcd)
    end
  end
end

local pow2 = {1}
for i = 1, 200010 do
  pow2[i + 1] = (pow2[i] * 2) % mod
end

local ret = badd(pow2[xzero + 1], pow2[yzero + 1])
ret = bsub(ret, 1)

local m1 = {}
for i1 = 1, #x1 do
  local xs, ys = x1[i1], y1[i1]
  if not m1[xs] then m1[xs] = {} end
  if not m1[xs][ys] then
    m1[xs][ys] = 1
  else
    m1[xs][ys] = m1[xs][ys] + 1
  end
end

local m2 = {}
for i2 = 1, #x2 do
  local xs, ys = x2[i2], y2[i2]
  if not m2[ys] then m2[ys] = {} end
  if not m2[ys][xs] then
    m2[ys][xs] = 1
  else
    m2[ys][xs] = m2[ys][xs] + 1
  end
end
for k1, v in pairs(m1) do
  if m2[k1] then
    local m2k1 = m2[k1]
    for k2, c1 in pairs(v) do
      local c2 = m2k1[k2]
      if c2 then
        ret = bmul(ret, bsub(badd(pow2[c1 + 1], pow2[c2 + 1]), 1))
        m2k1[k2] = nil
      else
        ret = bmul(ret, pow2[c1 + 1])
      end
    end
  else
    for k2, c1 in pairs(v) do
      ret = bmul(ret, pow2[c1 + 1])
    end
  end
end
for k1, v in pairs(m2) do
  for k2, c in pairs(v) do
    ret = bmul(ret, pow2[c + 1])
  end
end
ret = bsub(ret, 1)
ret = badd(ret, zero)
print(ret)


local mod = 1000000007
local mfl = math.floor

local function bmul(x, y)
  local x1, y1 = mfl(x / 31623), mfl(y / 31623)
  local x0, y0 = x - x1 * 31623, y - y1 * 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 getgcd(x, y)
  while 0LL < x do
    x, y = y % x, x
  end
  return y
end

local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
long long atoll(const char*);
]]

local function lltonumber(str)
  return C.atoll(str)
end

local x1, y1 = {}, {}
local x2, y2 = {}, {}
local xzero = 0
local yzero = 0
local haszero = false

local n = io.read("*n", "*l")
local a, b = {}, {}
for i = 1, n do
  local s = io.read()
  local ai, bi = s:match("(%-?%d+) (%-?%d+)")
  a[i] = lltonumber(ai)
  b[i] = lltonumber(bi)
  if a[i] == 0LL and b[i] == 0LL then
    haszero = true
  elseif a[i] == 0LL then
    xzero = xzero + 1
  elseif b[i] == 0LL then
    yzero = yzero + 1
  else
    if b[i] < 0LL then
      a[i], b[i] = -a[i], -b[i]
    end
    if 0LL < a[i] then
      local xi = a[i]
      local yi = b[i]
      local gcd = getgcd(xi, yi)
      table.insert(x1, xi / gcd)
      table.insert(y1, yi / gcd)
    else
      local xi = -a[i]
      local yi = b[i]
      local gcd = getgcd(xi, yi)
      table.insert(x2, xi / gcd)
      table.insert(y2, yi / gcd)
    end
  end
end
-- print(os.clock())
-- local idx1 = {}
-- for i = 1, #x1 do
--   idx1[i] = i
-- end
-- local idx2 = {}
-- for i = 1, #x2 do
--   idx2[i] = i
-- end
-- table.sort(idx1, function(aa, bb)
--   if x1[aa] ~= x1[bb] then
--     return x1[aa] < x1[bb]
--   else
--     return y1[aa] < y1[bb]
--   end
-- end)
--
-- table.sort(idx2, function(aa, bb)
--   if y2[aa] ~= y2[bb] then
--     return y2[aa] < y2[bb]
--   else
--     return x2[aa] < x2[bb]
--   end
-- end)

local pow2 = {1}
for i = 1, 200010 do
  pow2[i + 1] = (pow2[i] * 2) % mod
end

local ret = badd(pow2[xzero + 1], pow2[yzero + 1])
ret = bsub(ret, 1)

local m1 = {}
for i1 = 1, #x1 do
  local xs, ys = tostring(x1[i1]), tostring(y1[i1])
  if not m1[xs] then m1[xs] = {} end
  if not m1[xs][ys] then
    m1[xs][ys] = 1
  else
    m1[xs][ys] = m1[xs][ys] + 1
  end
end

local m2 = {}
for i2 = 1, #x2 do
  local xs, ys = tostring(x2[i2]), tostring(y2[i2])
  if not m2[ys] then m2[ys] = {} end
  if not m2[ys][xs] then
    m2[ys][xs] = 1
  else
    m2[ys][xs] = m2[ys][xs] + 1
  end
end
for k1, v in pairs(m1) do
  if m2[k1] then
    local m2k1 = m2[k1]
    for k2, c1 in pairs(v) do
      local c2 = m2k1[k2]
      if c2 then
        ret = bmul(ret, bsub(badd(pow2[c1 + 1], pow2[c2 + 1]), 1))
        m2k1[k2] = nil
      else
        ret = bmul(ret, pow2[c1 + 1])
      end
    end
  else
    for k2, c1 in pairs(v) do
      ret = bmul(ret, pow2[c1 + 1])
    end
  end
end
for k1, v in pairs(m2) do
  for k2, c in pairs(v) do
    ret = bmul(ret, pow2[c + 1])
  end
end
if not haszero then
  ret = bsub(ret, 1)
end
print(ret)


S=io.read()
T=io.read()
print((
	S==T:sub(1,-2)
)and"Yes"or"No")

Score : 100 points

Problem Statement

Takahashi wants to be a member of some web service.

He tried to register himself with the ID S, which turned out to be already used by another user.

Thus, he decides to register using a string obtained by appending one character at the end of S as his ID.

He is now trying to register with the ID T. Determine whether this string satisfies the property above.

Constraints

S and T are strings consisting of lowercase English letters.

1 \leq |S| \leq 10

|T| = |S| + 1

Input

Input is given from Standard Input in the following format:

S
T

Output

If T satisfies the property in Problem Statement, print Yes; otherwise, print No.

Sample Input 1

chokudai
chokudaiz

Sample Output 1

Yes

chokudaiz can be obtained by appending z at the end of chokudai.

Sample Input 2

snuke
snekee

Sample Output 2

No

snekee cannot be obtained by appending one character at the end of snuke.

Sample Input 3

a
aa

Sample Output 3

Yes


a,b,c,k=io.read("*n","*n","*n","*n")
if a+b>=k then
    print(math.min(a,k))
elseif a+b<k then
    if a+b+c==k then
        print(a+b-c)
    elseif a+b+c>k then
        print(a+b-(k-a-b))
    end
end

Score : 200 points

Problem Statement

We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.

We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?

Constraints

All values in input are integers.

0 \leq A, B, C

1 \leq K \leq A + B + C \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the maximum possible sum of the numbers written on the cards chosen.

Sample Input 1

2 1 1 3

Sample Output 1

2

Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value.

Sample Input 2

1 2 3 4

Sample Output 2

0

Sample Input 3

2000000000 0 0 2000000000

Sample Output 3

2000000000


a, b = io.read("*n", "*n")
c, k = io.read("*n", "*n")
local mmi, mma = math.min, math.max
r = 0
v = mmi(a, k)
r = r + v
k = k - v

v = mmi(b, k)
k = k - v
v = mmi(c, k)
r = r - v
print(r)


bit=require("bit")
n,m,x=io.read("*n","*n","*n","*l")
c={}
a={}
for i=1,n do
    c[i]=io.read("*n")
    a[i]={}
    for j=1,m do
        a[i][j]=io.read("*n")
    end
end

total=-1
for i=0,bit.lshift(1,n)-1 do
    icopy=i
    price=0
    xable={}
    for j=1,m do
        xable[j]=0
    end
    for j=1,n do
        if icopy%2==1 then
            for k=1,m do
                xable[k]=xable[k]+a[j][k]
            end
            price=price+c[j]
        end
        icopy=bit.rshift(icopy,1)
    end
    xbove=true
    for j=1,m do
        if xable[j]<x then
            xbove=false
        end
    end
    if xbove then
        if total==-1 then
            total=price
        else
            total=math.min(total,price)
        end
    end
end
print(total)

Score : 300 points

Problem

Takahashi, who is a novice in competitive programming, wants to learn M algorithms.
Initially, his understanding level of each of the M algorithms is 0.

Takahashi is visiting a bookstore, where he finds N books on algorithms.
The i-th book (1\leq i\leq N) is sold for C_i yen (the currency of Japan). If he buys and reads it, his understanding level of the j-th algorithm will increase by A_{i,j} for each j (1\leq j\leq M).
There is no other way to increase the understanding levels of the algorithms.

Takahashi's objective is to make his understanding levels of all the M algorithms X or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve it.

Constraints

All values in input are integers.

1\leq N, M\leq 12

1\leq X\leq 10^5

1\leq C_i \leq 10^5

0\leq A_{i, j} \leq 10^5

Input

Input is given from Standard Input in the following format:

N M X
C_1 A_{1,1} A_{1,2} \cdots A_{1,M}
C_2 A_{2,1} A_{2,2} \cdots A_{2,M}
\vdots
C_N A_{N,1} A_{N,2} \cdots A_{N,M}

Output

If the objective is not achievable, print -1; otherwise, print the minimum amount of money needed to achieve it.

Sample Input 1

3 3 10
60 2 2 4
70 8 7 9
50 2 3 9

Sample Output 1

120

Buying the second and third books makes his understanding levels of all the algorithms 10 or higher, at the minimum cost possible.

Sample Input 2

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

Sample Output 2

-1

Buying all the books is still not enough to make his understanding levels of all the algorithms 10 or higher.

Sample Input 3

8 5 22
100 3 7 5 3 1
164 4 5 2 7 8
334 7 2 7 2 9
234 4 7 2 8 2
541 5 4 3 3 6
235 4 8 6 9 7
394 3 6 1 6 2
872 8 4 3 7 2

Sample Output 3

1067


local bit=require"bit"
N=io.read"*n"
M=io.read"*n"
X=io.read"*n"
C={}
A={}
for i=1,N do
	C[i]=io.read"*n"
	A[i]={}
	for j=1,M do
		A[i][j]=io.read"*n"
	end
end

local min=math.huge
for i=0,2^N-1 do
	local t={0,0,0,0,0,0,0,0,0,0,0,0}
	local c=0
	for j=0,N-1 do
		if(bit.band(bit.rshift(i,j),1)~=0)then
			for k=1,M do
				t[k]=t[k]+A[j+1][k]
			end
			c=c+C[j+1]
		end
	end
	local b=true
	for k=1,M do
		if(t[k]<X)then b=false break end
	end
	if(b)then min=math.min(min,c)end
end
print(min==math.huge and -1 or min)


local mmi, mma = math.min, math.max
local n = io.read("*n", "*l")
local s = {}
local up, down = {}, {}
for i = 1, n do
  s[i] = io.read()
  local cur = 0
  local min = 0
  for j = 1, #s[i] do
    if s[i]:sub(j, j) == "(" then
      cur = cur + 1
    else
      cur = cur - 1
    end
    min = mmi(min, cur)
  end
  local dec = -min
  if 0 < cur then
    table.insert(up, {dec, cur})
  else
    table.insert(down, {dec, cur})
  end
end

local function sort1(a, b)
  return a[1] < b[1]
end
local function sort2(a, b)
  return a[1] > b[1]
end
table.sort(up, sort1)
table.sort(down, sort2)
local cur = 0
local valid = true
for i = 1, n do
  local dec, tot = 0, 0
  if i <= #up then
    dec, tot = up[i][1], up[i][2]
  else
    local p = i - #up
    dec, tot = down[p][1], down[p][2]
  end
  if cur - dec < 0 then
    valid = false
    break
  end
  cur = cur + tot
end
valid = valid and cur == 0
print(valid and "Yes" or "No")

Score : 600 points

Problem Statement

A bracket sequence is a string that is one of the following:

An empty string;

The concatenation of (, A, and ) in this order, for some bracket sequence A ;

The concatenation of A and B in this order, for some non-empty bracket sequences A and B /

Given are N strings S_i. Can a bracket sequence be formed by concatenating all the N strings in some order?

Constraints

1 \leq N \leq 10^6

The total length of the strings S_i is at most 10^6.

S_i is a non-empty string consisting of ( and ).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If a bracket sequence can be formed by concatenating all the N strings in some order, print Yes; otherwise, print No.

Sample Input 1

2
)
(()

Sample Output 1

Yes

Concatenating (() and ) in this order forms a bracket sequence.

Sample Input 2

2
)(
()

Sample Output 2

No

Sample Input 3

4
((()))
((((((
))))))
()()()

Sample Output 3

Yes

Sample Input 4

3
(((
)
)

Sample Output 4

No


s=io.read()
if s=="ABC" then
    print("ARC")
else
    print("ABC")
end

Score : 100 points

Problem Statement

AtCoder Inc. holds a contest every Saturday.

There are two types of contests called ABC and ARC, and just one of them is held at a time.

The company holds these two types of contests alternately: an ARC follows an ABC and vice versa.

Given a string S representing the type of the contest held last week, print the string representing the type of the contest held this week.

Constraints

S is ABC or ARC.

Input

Input is given from Standard Input in the following format:

S

Output

Print the string representing the type of the contest held this week.

Sample Input 1

ABC

Sample Output 1

ARC

They held an ABC last week, so they will hold an ARC this week.


s=io.read()
if s=="ABC" then
    print("ARC")
else
    print("ARC")
end


s = io.read()
print(s == "ABC" and "ARC" or "ABC")


n,k=io.read("*n","*n","*l")
snuke={}
for i=1,n do
    snuke[i]=1
end
a={}
for i=1,k do
    a[i]={}
    d=io.read("*n","*l")
    for j=1,d do
        a[i][j]=io.read("*n")
        if snuke[a[i][j]]==1 then
            snuke[a[i][j]]=0
        end
    end
end

counter=0
for i=1,n do
    counter=counter+snuke[i]
end
print(counter)

Score : 200 points

Problem Statement

N Snukes called Snuke 1, Snuke 2, ..., Snuke N live in a town.

There are K kinds of snacks sold in this town, called Snack 1, Snack 2, ..., Snack K. The following d_i Snukes have Snack i: Snuke A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}.

Takahashi will walk around this town and make mischief on the Snukes who have no snacks. How many Snukes will fall victim to Takahashi's mischief?

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 100

1 \leq d_i \leq N

1 \leq A_{i, 1} < \cdots < A_{i, d_i} \leq N

Input

Input is given from Standard Input in the following format:

N K
d_1
A_{1, 1} \cdots A_{1, d_1}
\vdots
d_K
A_{K, 1} \cdots A_{K, d_K}

Output

Print the answer.

Sample Input 1

3 2
2
1 3
1
3

Sample Output 1

1

Snuke 1 has Snack 1.

Snuke 2 has no snacks.

Snuke 3 has Snack 1 and 2.

Thus, there will be one victim: Snuke 2.

Sample Input 2

3 3
1
3
1
3
1
3

Sample Output 2

2


local n, k = io.read("*n", "*n")
local t = {}
for i = 1, n do t[i] = false end
for i = 1, k do
  local d = io.read("*n")
  for j = 1, d do
    x = io.read("*n")
    t[x] = true
  end
end
c = 0
for i = 1, n do
  if not t[i] then c = c + 1 end
end
print(c)


local function reada(n,m)m=m or 1 r={}for i=1,m do r[i]={}end for i=1,n do for j=1,m do r[j][i]=io.read"*n"end end return unpack(r)end
N=io.read"*n"
M=io.read"*n"
H=reada(N)

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

for i=1,M do
	a=io.read"*n"
	b=io.read"*n"
	table.insert(t[a],b)
	table.insert(t[b],a)
end
s=0
for i=1,N do
	b=true
	for j=1,#t[i]do
		if(H[t[i][j]]>=H[i])then b=false break end
	end
	if(b)then s=s+1 end
end
print(s)

Score : 300 points

Problem Statement

There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i.
There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.

Obs. i is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road.
Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road.

How many good observatories are there?

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq H_i \leq 10^9

1 \leq A_i,B_i \leq N

A_i \neq B_i

Multiple roads may connect the same pair of observatories.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
H_1 H_2 ... H_N
A_1 B_1
A_2 B_2
:
A_M B_M

Output

Print the number of good observatories.

Sample Input 1

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

Sample Output 1

2

From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good.

From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good.

From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good.

From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good.

Thus, the good observatories are Obs. 3 and 4, so there are two good observatories.

Sample Input 2

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

Sample Output 2

3


x=io.read("*n")
local range
for i=0,1000000000 do
    if i*i*i*i*i-(i-1)*(i-1)*(i-1)*(i-1)*(i-1)>=1000000000 then
        range=i
        break
    end
end

for i=-range,range do
    for j=-range,range do
        if i*i*i*i*i-j*j*j*j*j==x then
            print(i.." "..j)
            return
        end
    end
end

Score : 400 points

Problem Statement

Give a pair of integers (A, B) such that A^5-B^5 = X.
It is guaranteed that there exists such a pair for the given integer X.

Constraints

1 \leq X \leq 10^9

X is an integer.

There exists a pair of integers (A, B) satisfying the condition in Problem Statement.

Input

Input is given from Standard Input in the following format:

X

Output

Print A and B, with space in between.
If there are multiple pairs of integers (A, B) satisfying the condition, you may print any of them.

A B

Sample Input 1

33

Sample Output 1

2 -1

For A=2 and B=-1, A^5-B^5 = 33.

Sample Input 2

1

Sample Output 2

0 -1


local function reada(n,m)m=m or 1 r={}for i=1,m do r[i]={}end for i=1,n do for j=1,m do r[j][i]=io.read"*n"end end return unpack(r)end
N=io.read"*n"
A=reada(N)

s=0
for i=1,N do
for j=i+A[i]+1,N do
	if(A[i]+A[j]==j-i)then s=s+1 end
end
end
print(s)

Score: 500 points

Problem Statement

You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens.

There are N attendees in the party, and they are given attendee numbers from 1 through N. The height of Attendee i is A_i.

According to an examination beforehand, you know that a pair of attendees satisfying the condition below will make the transaction.

The absolute difference of their attendee numbers is equal to the sum of their heights.

There are \frac{N(N-1)}{2} ways to choose two from the N attendees and make a pair. Among them, how many satisfy the condition above?

P.S.: We cannot let you know the secret.

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the number of pairs satisfying the condition.

Sample Input 1

6
2 3 3 1 3 1

Sample Output 1

3

A_1 + A_4 = 3, so the pair of Attendee 1 and 4 satisfy the condition.

A_2 + A_6 = 4, so the pair of Attendee 2 and 6 satisfy the condition.

A_4 + A_6 = 2, so the pair of Attendee 4 and 6 satisfy the condition.

No other pair satisfies the condition, so you should print 3.

Sample Input 2

6
5 2 4 2 8 8

Sample Output 2

0

No pair satisfies the condition, so you should print 0.

Sample Input 3

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

Sample Output 3

22


local q, a, b, c = io.read("*n", "*n", "*n", "*n", "*l")
local op = {}
for i = 1, q do
  op[i] = io.read()
end
if a + b + c == 0 then
  print("No")
  os.exit()
elseif a + b + c == 1 then
  local ret = {}
  local valid = true
  for iq = 1, q do
    if op[iq] == "AB" then
      if a == 1 then
        ret[iq] = "B"
        a, b = 0, 1
      elseif b == 1 then
        ret[iq] = "A"
        a, b = 1, 0
      else
        valid = false break
      end
    elseif op[iq] == "BC" then
      if b == 1 then
        ret[iq] = "C"
        b, c = 0, 1
      elseif c == 1 then
        ret[iq] = "B"
        b, c = 1, 0
      else
        valid = false break
      end
    else
      if a == 1 then
        ret[iq] = "C"
        a, c = 0, 1
      elseif c == 1 then
        ret[iq] = "A"
        a, c = 1, 0
      else
        valid = false break
      end
    end
  end
  if valid then
    print("Yes")
    print(table.concat(ret, "\n"))
  else
    print("No")
  end
  os.exit()
elseif 3 <= a + b + c then
  if a + b == 0 and op[1] == "AB" then
    print("No") os.exit()
  elseif b + c == 0 and op[1] == "BC" then
    print("No") os.exit()
  elseif a + c == 0 and op[1] == "AC" then
    print("No") os.exit()
  end
  local ret = {}
  for iq = 1, q do
    if op[iq] == "AB" then
      if a < b then
        ret[iq] = "A"
        a, b = a + 1, b - 1
      else
        ret[iq] = "B"
        a, b = a - 1, b + 1
      end
    elseif op[iq] == "BC" then
      if b < c then
        ret[iq] = "B"
        b, c = b + 1, c - 1
      else
        ret[iq] = "C"
        b, c = b - 1, c + 1
      end
    else
      if a < c then
        ret[iq] = "A"
        a, c = a + 1, c - 1
      else
        ret[iq] = "C"
        a, c = a - 1, c + 1
      end
    end
  end
  print("Yes")
  print(table.concat(ret, "\n"))
  os.exit()
end
-- a + b + c == 2
local dp = {}
for j = 1, q + 1 do
  dp[j] = {}
  -- 110, 101, 011, 200, 020, 002
  for i = 1, 6 do
    dp[j][i] = false
  end
end
if a == 1 and b == 1 then
  dp[1][1] = true
elseif a == 1 and c == 1 then
  dp[1][2] = true
elseif b == 1 and c == 1 then
  dp[1][3] = true
elseif a == 2 then
  dp[1][4] = true
elseif b == 2 then
  dp[1][5] = true
else
  dp[1][6] = true
end
for i = 1, q do
  if op[i] == "AB" then
    if dp[i][1] then
      dp[i + 1][4] = true
      dp[i + 1][5] = true
    end
    if dp[i][2] then
      dp[i + 1][3] = true
    end
    if dp[i][3] then
      dp[i + 1][2] = true
    end
    if dp[i][4] or dp[i][5] then
      dp[i + 1][1] = true
    end
  elseif op[i] == "BC" then
    if dp[i][3] then
      dp[i + 1][5] = true
      dp[i + 1][6] = true
    end
    if dp[i][2] then
      dp[i + 1][1] = true
    end
    if dp[i][1] then
      dp[i + 1][2] = true
    end
    if dp[i][5] or dp[i][6] then
      dp[i + 1][3] = true
    end
  else
    if dp[i][2] then
      dp[i + 1][4] = true
      dp[i + 1][6] = true
    end
    if dp[i][1] then
      dp[i + 1][3] = true
    end
    if dp[i][3] then
      dp[i + 1][1] = true
    end
    if dp[i][4] or dp[i][6] then
      dp[i + 1][2] = true
    end
  end
end
local cur = false
for i = 1, 6 do
  if dp[q + 1][i] then
    cur = i
    break
  end
end
if not cur then
  print("No")
  os.exit()
end
local ret = {}
for i = 1, q do ret[i] = 0 end
for i = q, 1, -1 do
  local iq = i
  -- print(cur)
  if op[iq] == "AB" then
    if cur == 1 then
      if dp[i][4] then
        ret[i] = "B"
        cur = 4
      else--5
        ret[i] = "A"
        cur = 5
      end
    elseif cur == 2 then
      ret[i] = "A"
      cur = 3
    elseif cur == 3 then
      ret[i] = "B"
      cur = 2
    elseif cur == 4 then
      ret[i] = "A"
      cur = 1
    else-- 5
      ret[i] = "B"
      cur = 1
    end
  elseif op[iq] == "BC" then
    if cur == 3 then
      if dp[i][5] then
        ret[i] = "C"
        cur = 5
      else--6
        ret[i] = "B"
        cur = 6
      end
    elseif cur == 1 then
      ret[i] = "B"
      cur = 2
    elseif cur == 2 then
      ret[i] = "C"
      cur = 1
    elseif cur == 5 then
      ret[i] = "B"
      cur = 3
    else-- 6
      ret[i] = "C"
      cur = 3
    end
  else
    if cur == 2 then
      if dp[i][4] then
        ret[i] = "C"
        cur = 4
      else--6
        ret[i] = "A"
        cur = 6
      end
    elseif cur == 1 then
      ret[i] = "A"
      cur = 3
    elseif cur == 3 then
      ret[i] = "C"
      cur = 1
    elseif cur == 4 then
      ret[i] = "A"
      cur = 2
    else-- 6
      ret[i] = "C"
      cur = 2
    end
  end
end
print("Yes")
print(table.concat(ret, "\n"))

Score : 600 points

Problem Statement

There is a game that involves three variables, denoted A, B, and C.

As the game progresses, there will be N events where you are asked to make a choice.
Each of these choices is represented by a string s_i. If s_i is AB, you must add 1 to A or B then subtract 1 from the other; if s_i is AC, you must add 1 to A or C then subtract 1 from the other; if s_i is BC, you must add 1 to B or C then subtract 1 from the other.

After each choice, none of A, B, and C should be negative.

Determine whether it is possible to make N choices under this condition. If it is possible, also give one such way to make the choices.

Constraints

1 \leq N \leq 10^5

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

N, A, B, C are integers.

s_i is AB, AC, or BC.

Input

Input is given from Standard Input in the following format:

N A B C
s_1
s_2
:
s_N

Output

If it is possible to make N choices under the condition, print Yes; otherwise, print No.

Also, in the former case, show one such way to make the choices in the subsequent N lines. The (i+1)-th line should contain the name of the variable (A, B, or C) to which you add 1 in the i-th choice.

Sample Input 1

2 1 3 0
AB
AC

Sample Output 1

Yes
A
C

You can successfully make two choices, as follows:

In the first choice, add 1 to A and subtract 1 from B. A becomes 2, and B becomes 2.

In the second choice, add 1 to C and subtract 1 from A. C becomes 1, and A becomes 1.

Sample Input 2

3 1 0 0
AB
BC
AB

Sample Output 2

No

Sample Input 3

1 0 9 0
AC

Sample Output 3

No

Sample Input 4

8 6 9 1
AC
BC
AB
BC
AC
BC
AB
AB

Sample Output 4

Yes
C
B
B
C
C
B
A
A


K=io.read"*n"
A=io.read"*n"
B=io.read"*n"
print((function()
	for i=A,B do
		if(i%K==0)then return true end
	end
return false end)()and"OK"or"NG")

Score: 100 points

Problem Statement

Takahashi the Jumbo will practice golf.

His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).

If he can achieve the objective, print OK; if he cannot, print NG.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 1000

1 \leq K \leq 1000

Input

Input is given from Standard Input in the following format:

K
A B

Output

If he can achieve the objective, print OK; if he cannot, print NG.

Sample Input 1

7
500 600

Sample Output 1

OK

Among the multiples of 7, for example, 567 lies between 500 and 600.

Sample Input 2

4
5 7

Sample Output 2

NG

No multiple of 4 lies between 5 and 7.

Sample Input 3

1
11 11

Sample Output 3

OK


local x=io.read("n")
local yokin=100
local counter=0
while yokin<x do
    yokin=math.floor(yokin*101/100)
    counter=counter+1
end
print(counter)

Score : 200 points

Problem Statement

Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.

The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)

Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or above for the first time?

Constraints

101 \le X \le 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of years it takes for Takahashi's balance to reach X yen or above for the first time.

Sample Input 1

103

Sample Output 1

3

The balance after one year is 101 yen.

The balance after two years is 102 yen.

The balance after three years is 103 yen.

Thus, it takes three years for the balance to reach 103 yen or above.

Sample Input 2

1000000000000000000

Sample Output 2

3760

Sample Input 3

1333333333

Sample Output 3

1706


money = 100
X = tonumber(io.read())

year = 0
while money < X do
	money = money + math.floor(money/100)
	year = year + 1
end

print(year)


local mmi, mma = math.min, math.max
local mfl, mce = math.floor, math.ceil
local n, m, q = io.read("*n", "*n", "*n")
local t = {}
for iq = 1, q do
  local a, b, c, d = io.read("*n", "*n", "*n", "*n")
  t[iq] = {a, b, c, d}
end

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

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

local combmap = combination_get_map(n + m - 1)
local combcnt = combination_get_count(combmap, n + m - 1, n)
local ans = 0
for i = 1, combcnt do
  local ary = combination_get_array(combmap, n + m - 1, n, i)
  for j = 1, n do
    ary[j] = ary[j] - j + 1
  end
  local r = 0
  for iq = 1, q do
    local a, b, c, d = unpack(t[iq])
    if ary[b] - ary[a] == c then
      r = r + d
    end
  end
  ans = mma(ans, r)
end
print(ans)

Score : 300 points

Problem Statement

Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).

Consider a sequence A satisfying the following conditions:

A is a sequence of N positive integers.

1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.

Let us define a score of this sequence as follows:

The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.)

Find the maximum possible score of A.

Constraints

All values in input are integers.

2 ≤ N ≤ 10

1 \leq M \leq 10

1 \leq Q \leq 50

1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q )

0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q )

(a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j)

1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q )

Input

Input is given from Standard Input in the following format:

N M Q
a_1 b_1 c_1 d_1
:
a_Q b_Q c_Q d_Q

Output

Print the maximum possible score of A.

Sample Input 1

3 4 3
1 3 3 100
1 2 2 10
2 3 2 10

Sample Output 1

110

When A = \{1, 3, 4\}, its score is 110. Under these conditions, no sequence has a score greater than 110, so the answer is 110.

Sample Input 2

4 6 10
2 4 1 86568
1 4 0 90629
2 3 0 90310
3 4 1 29211
3 4 3 78537
3 4 2 8580
1 2 1 96263
1 4 2 2156
1 2 0 94325
1 4 3 94328

Sample Output 2

357500

Sample Input 3

10 10 1
1 10 9 1

Sample Output 3

1


local a,b,n=io.read("n","n","n")
local answer=-10^20
for i=(n>b and b or n),1,-1 do
    local x=math.floor(a*i/b)-a*math.floor(i/b)
    if answer<x then
        answer=x
    else
        break
    end
end
print(answer)

Score : 400 points

Problem Statement

Given are integers A, B, and N.

Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.

Here floor(t) denotes the greatest integer not greater than the real number t.

Constraints

1 ≤ A ≤ 10^{6}

1 ≤ B ≤ 10^{12}

1 ≤ N ≤ 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B N

Output

Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.

Sample Input 1

5 7 4

Sample Output 1

2

When x=3, floor(Ax/B)-A×floor(x/B) = floor(15/7) - 5×floor(3/7) = 2. This is the maximum value possible.

Sample Input 2

11 10 9

Sample Output 2

9


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

local edge = {}
local asked = {}
local cpos = {}
local len = {}
local stpos = {}
for i = 1, n do
  edge[i] = {}
  asked[i] = false
  cpos[i] = 0
  len[i] = 0
  stpos[i] = 0
end
len[n + 1] = 1000000007
for i = 1, n - 1 do
  local x, y = io.read("*n", "*n")
  table.insert(edge[x], y)
  table.insert(edge[y], x)
end

local lis = {}
for i = 1, n + 1 do
  lis[i] = 1000000007
end
local ret = {}
for i = 1, n do ret[i] = 1 end
local tasks = {1}
local undotask = {}
local sti = 1
while 0 < #tasks do
  local src = tasks[#tasks]
  table.remove(tasks)
  -- print(src)
  if src == -1 then
    local ubpos, v, z = undotask[#undotask][1], undotask[#undotask][2], undotask[#undotask][3]
    table.remove(undotask)
    lis[ubpos] = v
    -- print("UNDO", z, ubpos, v)
  else
    if not asked[src] then
      asked[src] = true
      local ubpos = lower_bound(lis, t[src])
      table.insert(undotask, {ubpos, lis[ubpos], src})
      -- print("ADD", src, ubpos, lis[ubpos])
      lis[ubpos] = t[src]
      local r = lower_bound(lis, 1000000007) - 1
      ret[src] = r
    end
    -- print(src, len[src])
    stpos[src] = sti
    sti = sti + 1
    while cpos[src] < #edge[src] do
      cpos[src] = cpos[src] + 1
      local dst = edge[src][cpos[src]]
      if not asked[dst] then
        len[dst] = len[src] + 1
        table.insert(tasks, src)
        table.insert(tasks, -1)
        table.insert(tasks, dst)
        break
      end
    end
  end
end
print(table.concat(ret, "\n"))

Score : 600 points

Problem Statement

We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i.
Vertex i has an integer a_i written on it.
For every integer k from 1 through N, solve the following problem:

We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.

Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.

Constraints

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

1 \leq a_i \leq 10^9

1 \leq u_i , v_i \leq N

u_i \neq v_i

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.

Sample Input 1

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

Sample Output 1

1
2
3
3
4
4
5
2
2
3

For example, the sequence A obtained from the shortest path from Vertex 1 to Vertex 5 is 1,2,5,3,4. Its longest increasing subsequence is A_1, A_2, A_4, A_5, with the length of 4.


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) assert(type(default_val) ~= 'table') 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 S, W = read.nn()
if W >= S then
    print("unsafe")
else
    print("safe")
end

Score : 100 points

Problem Statement

There are S sheep and W wolves.

If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep.

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Constraints

1 \leq S \leq 100

1 \leq W \leq 100

Input

Input is given from Standard Input in the following format:

S W

Output

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Sample Input 1

4 5

Sample Output 1

unsafe

There are four sheep and five wolves. The number of wolves is not less than that of sheep, so they will attack them.

Sample Input 2

100 2

Sample Output 2

safe

Many a sheep drive away two wolves.

Sample Input 3

10 10

Sample Output 3

unsafe


n = io.read()
n = tonumber(n)
t = {}
for i = 1, n do
  s = io.read()
  t[s] = true
end
c = 0
for k, _u in pairs(t) do
  c = c + 1
end
print(c)

Score : 300 points

Problem Statement

You drew lottery N times. In the i-th draw, you got an item of the kind represented by a string S_i.

How many kinds of items did you get?

Constraints

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

S_i consists of lowercase English letters and has a length between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print the number of kinds of items you got.

Sample Input 1

3
apple
orange
apple

Sample Output 1

2

You got two kinds of items: apple and orange.

Sample Input 2

5
grape
grape
grape
grape
grape

Sample Output 2

1

Sample Input 3

4
aaaa
a
aaa
aa

Sample Output 3

4


n,m=io.read("*n","*n","*l")
sum=0
for i=1,m do
    sum=sum+io.read("*n")
end

if sum>n then
    print(-1)
    return
else
    print(n-sum)
end

Score : 200 points

Problem Statement

Takahashi has N days of summer vacation.

His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.

He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.

What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation?

If Takahashi cannot finish all the assignments during the vacation, print -1 instead.

Constraints

1 \leq N \leq 10^6

1 \leq M \leq 10^4

1 \leq A_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 ... A_M

Output

Print the maximum number of days Takahashi can hang out during the vacation, or -1.

Sample Input 1

41 2
5 6

Sample Output 1

30

For example, he can do the first assignment on the first 5 days, hang out on the next 30 days, and do the second assignment on the last 6 days of the vacation. In this way, he can safely spend 30 days hanging out.

Sample Input 2

10 2
5 6

Sample Output 2

-1

He cannot finish his assignments.

Sample Input 3

11 2
5 6

Sample Output 3

0

He can finish his assignments, but he will have no time to hang out.

Sample Input 4

314 15
9 26 5 35 8 9 79 3 23 8 46 2 6 43 3

Sample Output 4

9


local ffi=require"ffi"
local modint
do
local MOD=1000000007
local mt={}
modint=setmetatable({new=function(x)return setmetatable({v=x},mt)end},{__call=function(o,x)return setmetatable({v=x%MOD},mt)end})
local function add(a,b)return (a+b)%MOD end
function mt.__add(a,b) return modint.new(add(a.v,b.v))end
local function sub(a,b)return (a-b)%MOD end
function mt.__sub(a,b) return modint.new(sub(a.v,b.v))end
local function mul(a,b)
	local ret=0
	while(b>0)do
		if(b%2==1)then ret=(ret+a)%MOD end
		a=(a+a)%MOD
		b=math.floor(b*.5)
	end
	return ret
end
function mt.__mul(a,b)
	a=a.v b=b.v
	return modint(a<b and mul(b,a)or mul(a,b))
end
local function pow(a,b)
	local ret=1
	while(b>0)do
		if(b%2==1)then ret=mul(ret,a)end
		a=mul(a,a)
		b=math.floor(b*.5)
	end
	return ret
end
function mt.__pow(a,b)return modint(pow(a.v,b.v))end
local function inv(x)
local a=x
local b,u,v=MOD,1,0
repeat
local t=math.floor(a/b)
a,b=b,a-t*b
u,v=v,u-t*v
until(b==0)
return u
end
local function div(a,b)return mul(a,inv(b))end
function mt.__div(a,b)return modint.new(div(a.v,b.v))end
function mt.__tostring(x)return tostring(x.v)end
local method={}
mt.__index=method
function method.inv(x)return modint.new(inv(x.v))end
do
local MAX=510000
local ct=ffi.typeof("int[$]",MAX)
local fac=ffi.new(ct,{1,1})
local inv=ffi.new(ct,{1,1})
local finv=ffi.new(ct,{1,1})
for i=2,MAX-1 do
fac[i]=mul(fac[i-1],i)
inv[i]=MOD-mul(inv[MOD%i],math.floor(MOD/i))
finv[i]=mul(finv[i-1],inv[i])
end
function method.C(n,k)
n=n.v k=k.v
if(n<k)then return 0 end
return mul(mul(finv[k],finv[n-k]),fac[n])
end
end
end --modint define

N=io.read"*n"
K=io.read"*n"

r=modint(0)
for i=K,N+1 do
local min=i*(i-1)/2
local max=(N-i+1+N)*i/2
r=r+modint(max-min+1)
end
print(r)


N=io.read()
a={}
for i=1, N do
    if i%3==0 and i%5==0 then
        a[i]="FizzBuzz"
    elseif i%3==0 then
        a[i]="Fizz"
    elseif i%5==0 then
        a[i]="Buzz"
    else
        a[i]=i
    end
end

sum = 0
for i=1, N do
    if type(a[i])=="number" then
        sum = sum + a[i]
    end
end
print(sum)

Score : 200 points

Problem Statement

Let us define the FizzBuzz sequence a_1,a_2,... as follows:

If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.

If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.

If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.

If none of the above holds, a_i=i.

Find the sum of all numbers among the first N terms of the FizzBuzz sequence.

Constraints

1 \leq N \leq 10^6

Input

Input is given from Standard Input in the following format:

N

Output

Print the sum of all numbers among the first N terms of the FizzBuzz sequence.

Sample Input 1

15

Sample Output 1

60

The first 15 terms of the FizzBuzz sequence are:

1,2,\mbox{Fizz},4,\mbox{Buzz},\mbox{Fizz},7,8,\mbox{Fizz},\mbox{Buzz},11,\mbox{Fizz},13,14,\mbox{FizzBuzz}

Among them, numbers are 1,2,4,7,8,11,13,14, and the sum of them is 60.

Sample Input 2

1000000

Sample Output 2

266666333332

Watch out for overflow.


Score : 300 points

Problem Statement

Given any integer x, Aoki can do the operation below.

Operation: Replace x with the absolute difference of x and K.

You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.

Constraints

0 ≤ N ≤ 10^{18}

1 ≤ K ≤ 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible value taken by N after Aoki does the operation zero or more times.

Sample Input 1

7 4

Sample Output 1

1

Initially, N=7.

After one operation, N becomes |7-4| = 3.

After two operations, N becomes |3-4| = 1, which is the minimum value taken by N.

Sample Input 2

2 6

Sample Output 2

2

N=2 after zero operations is the minimum.

Sample Input 3

1000000000000000000 1

Sample Output 3

0


local N, K = io.read("*n", "*n")

local function ans(n, k)
    local min = math.abs(n - k)
    if n < min then
        return n
    end
    return ans(min, k)
end

print(ans(N, K))


---- Quote(Alteration) ----
Queue = {}

function Queue.new()
    local obj = { buff = {}, top_index = 0}
    return setmetatable(obj,{__index = Queue})
end

function Queue:enqueue(x)
    table.insert(self.buff, x)
end

function Queue:dequeue()
    self.top_index = self.top_index + 1
    local value = self.buff[self.top_index]
    self.buff[self.top_index] = nil
    return value
end
--[[
function Queue:top()
    if #self.buff > 0 then
        return self.buff[self.top_index]
    end
end
--
function Queue:isEmpty()
    return #self.buff == 0
end
--]]
---- from http://www.nct9.ne.jp/m_hiroi/light/lua.html ----

--[[
ルンルン数の特徴:十以上の位がそれまでに出て来たルンルン数を流用している。
それゆえ、流用される側の数字の一の位に-1, 0, 1を加えた数と
流用される側の数字を10倍した数を足し、ルンルン数を生成する。
ただし、流用される側の数字の一の位の数字が0,9のときは生成しない場合を作っておく。
]]
local k = io.read("*n")
local lunluns = Queue.new()
for i = 1, 9 do
    lunluns:enqueue(i)
    if i == k then
        print(tostring(i)); os.exit()
    end
end

for i = 1, k do
    local x = 0LL + lunluns:dequeue()
    if x % 10 ~= 0 then
        lunluns:enqueue(10 * x + (x % 10) - 1)
        if #lunluns.buff == k then
            print(tostring(10 * x + (x % 10) - 1):sub(1, -3)); break
        end
    end
    lunluns:enqueue(10 * x + (x % 10))
    if #lunluns.buff == k then
        print(tostring(10 * x + (x % 10)):sub(1, -3)); break
    end
    if x % 10 ~= 9 then
        lunluns:enqueue(10 * x + (x % 10) + 1)
        if #lunluns.buff == k then
            print(tostring(10 * x + (x % 10) + 1):sub(1, -3)); break
        end
    end
end

Score : 400 points

Problem Statement

A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:

In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.

For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is.

You are given a positive integer K. Find the K-th smallest lunlun number.

Constraints

1 \leq K \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the answer.

Sample Input 1

15

Sample Output 1

23

We will list the 15 smallest lunlun numbers in ascending order:

1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
21,
22,
23.

Thus, the answer is 23.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

13

Sample Output 3

21

Sample Input 4

100000

Sample Output 4

3234566667

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


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

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

local function getdivisorparts(x, primes)
  local prime_num = #primes
  local tmp = {}
  local lim = mce(msq(x))
  local primepos = 1
  local dv = primes[primepos]
  while primepos <= prime_num and dv <= lim do
    if x % dv == 0 then
      local t = {}
      t.p = dv
      t.cnt = 1
      x = 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 = mfl(div / (divisorparts[i].cnt + 1))
      local mul = mfl(i_pat / div)
      i_pat = i_pat % div
      for j = 1, mul do
        ret = ret * divisorparts[i].p
      end
    end
    table.insert(t, ret)
  end
  -- table.sort(t)
  return t
end

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

local n = io.read("*n")
-- n = k^a * (bk + 1)
-- n = 1000 * 1000 * 1000 * 1000
-- 2 <= a
local a = 1
local ret = 0
while true do
  a = a + 1
  if n < (2^a) then break end
  local k = 1
  while true do
    k = k + 1
    local ka = 1
    for i = 1, a do
      ka = ka * k
    end
    if n < ka then
      --print(a, k, ka)
      break
    end
    if n % ka == 0 then
      local rem = mfl(n / ka)
      if rem % k == 1 then ret = ret + 1 end
    end
  end
end
-- a == 1
-- a == 1 and 0 < b
for k = 2, 1000000 do
  if k * k <= n then
    if n % (k * k) == k then ret = ret + 1 end
    -- local rem = mfl(n / (k * k))
    -- if rem % k == 1 then ret = ret + 1 end
  end
end
-- a == 1 and b == 0
if 2 < n then ret = ret + 1 end
-- a == 0
if 2 < n then
  local primes = getprimes(1000000)
  local divisor = getdivisor(n - 1, primes)
  -- print(table.concat(divisor, " "))
  ret = ret + #divisor - 1
end
print(ret)

Score : 600 points

Problem Statement

Given is a positive integer N.

We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K.

Operation: if K divides N, replace N with N/K; otherwise, replace N with N-K.

In how many choices of K will N become 1 in the end?

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of choices of K in which N becomes 1 in the end.

Sample Input 1

6

Sample Output 1

3

There are three choices of K in which N becomes 1 in the end: 2, 5, and 6.

In each of these choices, N will change as follows:

When K=2: 6 \to 3 \to 1

When K=5: 6 \to 1

When K=6: 6 \to 1

Sample Input 2

3141

Sample Output 2

13

Sample Input 3

314159265358

Sample Output 3

9


K,N=io.read("*n","*n")
A={}
for i=1,N do
A[i]={i,io.read"*n"}
end
table.sort(A,function(a,b)return a[2]<b[2]end)
B={}
for i=1,N-1 do
B[i]={i,A[i+1][2]-A[i][2]}
end
B[N]={N,K+A[1][2]-A[N][2]}
local max=B[1]
for i=2,N do
	if(B[i][2]>max[2])then max=B[i] end
end
print(K-max[2])

Score : 300 points

Problem Statement

There is a circular pond with a perimeter of K meters, and N houses around them.

The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints

2 \leq K \leq 10^6

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

0 \leq A_1 < ... < A_N < K

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K N
A_1 A_2 ... A_N

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.


Score : 100 points

Problem Statement

We have N+M balls, each of which has an integer written on it.

It is known that:

The numbers written on N of the balls are even.

The numbers written on M of the balls are odd.

Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.

It can be shown that this count does not depend on the actual values written on the balls.

Constraints

0 \leq N,M \leq 100

2 \leq N+M

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample Input 1

2 1

Sample Output 1

1

For example, let us assume that the numbers written on the three balls are 1,2,4.

If we choose the two balls with 1 and 2, the sum is odd;

If we choose the two balls with 1 and 4, the sum is odd;

If we choose the two balls with 2 and 4, the sum is even.

Thus, the answer is 1.

Sample Input 2

4 3

Sample Output 2

9

Sample Input 3

1 1

Sample Output 3

0

Sample Input 4

13 3

Sample Output 4

81

Sample Input 5

0 3

Sample Output 5

3


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

print((l / 3) ^ 3)

Score : 300 points

Problem Statement

Given is a positive integer L.
Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.

Constraints

1 ≤ L ≤ 1000

L is an integer.

Input

Input is given from Standard Input in the following format:

L

Output

Print the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.
Your output is considered correct if its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

3

Sample Output 1

1.000000000000

For example, a rectangular cuboid whose dimensions are 0.8, 1, and 1.2 has a volume of 0.96.

On the other hand, if the dimensions are 1, 1, and 1, the volume of the rectangular cuboid is 1, which is greater.

Sample Input 2

999

Sample Output 2

36926037.000000000000


local a = io.read("*n")
a = a / 3
print(a * a * a)


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

b={}
for i=1, n do
    if b[a[i]]==nil then
        b[a[i]]=1
    else
        b[a[i]]=b[a[i]]+1
    end
end

total=0
for key,value in pairs(b) do
    total=total+value*(value-1)//2
end

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

Score : 400 points

Problem Statement

We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.

Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

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

1 \leq A_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For each k=1,2,...,N, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5


local mod = 998244353
local mfl = math.floor
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 n, s = io.read("*n", "*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
local dp = {}
for i = 1, s + 1 do
  dp[i] = 0
end
dp[1] = 1
if a[n] <= s then
  dp[a[n] + 1] = 1
end
local ret = dp[s + 1]
for i = n - 1, 1, -1 do
  local av = a[i]
  dp[1] = badd(dp[1], 1)
  for j = s + 1 - av, 1, -1 do
    dp[j + av] = badd(dp[j + av], dp[j])
  end
  ret = badd(ret, dp[s + 1])
end
print(ret)

Score : 600 points

Problem Statement

Given are a sequence of N integers A_1, A_2, \ldots, A_N and a positive integer S.

For a pair of integers (L, R) such that 1\leq L \leq R \leq N, let us define f(L, R) as follows:

f(L, R) is the number of sequences of integers (x_1, x_2, \ldots , x_k) such that L \leq x_1 < x_2 < \cdots < x_k \leq R and A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.

Find the sum of f(L, R) over all pairs of integers (L, R) such that 1\leq L \leq R\leq N. Since this sum can be enormous, print it modulo 998244353.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq S \leq 3000

1 \leq A_i \leq 3000

Input

Input is given from Standard Input in the following format:

N S
A_1 A_2 ... A_N

Output

Print the sum of f(L, R), modulo 998244353.

Sample Input 1

3 4
2 2 4

Sample Output 1

5

The value of f(L, R) for each pair is as follows, for a total of 5.

f(1,1) = 0

f(1,2) = 1 (for the sequence (1, 2))

f(1,3) = 2 (for (1, 2) and (3))

f(2,2) = 0

f(2,3) = 1 (for (3))

f(3,3) = 1 (for (3))

Sample Input 2

5 8
9 9 9 9 9

Sample Output 2

0

Sample Input 3

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

Sample Output 3

152


local h,w=io.read("n","n","l")
local s={}
local dp={}
for i=1,h do
    local t=io.read()
    s[i]={}
    dp[i]={}
    for j=1,w do
        s[i][j]=t:sub(j,j)
        dp[i][j]=10000000000000000
    end
end

local dx={1,0}
local dy={0,1}

local function solve()
    if s[1][1]=="#" then
        dp[1][1]=1
    else
        dp[1][1]=0
    end

    for i=1,h do
        for j=1,w do
            for k=1,2 do
                local ni=i+dx[k]
                local nj=j+dy[k]
                if h>=ni and w>=nj then
                    local add=0
                    if s[ni][nj]=="#" and s[i][j]=="." then
                        add=1
                    end
                    if dp[ni][nj]>dp[i][j]+add then
                        dp[ni][nj]=dp[i][j]+add
                    end
                end
            end
        end
    end
    return dp[h][w]
end

print(solve())

Score : 400 points

Problem Statement

Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left.
Each square is painted black or white.

The grid is said to be good if and only if the following condition is satisfied:

From (1, 1), we can reach (H, W) by moving one square right or down repeatedly, while always being on a white square.

Note that (1, 1) and (H, W) must be white if the grid is good.

Your task is to make the grid good by repeating the operation below. Find the minimum number of operations needed to complete the task. It can be proved that you can always complete the task in a finite number of operations.

Choose four integers r_0, c_0, r_1, c_1(1 \leq r_0 \leq r_1 \leq H, 1 \leq c_0 \leq c_1 \leq W). For each pair r, c (r_0 \leq r \leq r_1, c_0 \leq c \leq c_1), invert the color of (r, c) - that is, from white to black and vice versa.

Constraints

2 \leq H, W \leq 100

Input

Input is given from Standard Input in the following format:

H W
s_{11} s_{12} \cdots s_{1W}
s_{21} s_{22} \cdots s_{2W}
\vdots
s_{H1} s_{H2} \cdots s_{HW}

Here s_{rc} represents the color of (r, c) - # stands for black, and . stands for white.

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

Do the operation with (r_0, c_0, r_1, c_1) = (2, 2, 2, 2) to change just the color of (2, 2), and we are done.

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

4 4
..##
#...
###.
###.

Sample Output 3

0

No operation may be needed.

Sample Input 4

5 5
.#.#.
#.#.#
.#.#.
#.#.#
.#.#.

Sample Output 4

4


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) assert(type(default_val) ~= 'table') 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 a = {1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51}
local K = read.n()
print(a[K])

Score : 100 points

Problem Statement

Print the K-th element of the following sequence of length 32:

1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51

Constraints

1 \leq K \leq 32

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the K-th element.

Sample Input 1

6

Sample Output 1

2

The 6-th element is 2.

Sample Input 2

27

Sample Output 2

5

The 27-th element is 5.