local mmi = math.min
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", "*l")
local s = ""

local function create()
  local struct = {}
  struct.xpy = {}
  struct.xmy = {}
  struct.x = {}
  struct.y = {}
  return struct
end
local toleft = create()
local toright = create()
local toup = create()
local todown = create()

local function ins(tbl, x, y)
  local xpy, xmy = x + y, x - y
  if not tbl.xpy[xpy] then tbl.xpy[xpy] = {} end
  table.insert(tbl.xpy[xpy], x)
  if not tbl.xmy[xmy] then tbl.xmy[xmy] = {} end
  table.insert(tbl.xmy[xmy], x)
  if not tbl.x[x] then tbl.x[x] = {} end
  table.insert(tbl.x[x], y)
  if not tbl.y[y] then tbl.y[y] = {} end
  table.insert(tbl.y[y], x)
end
local function sortall(tbl)
  local z = {tbl.xpy, tbl.xmy, tbl.x, tbl.y}
  for i = 1, 4 do
    for k, t in pairs(z[i]) do
      table.sort(t)
    end
  end
end

local raw_x, raw_y, raw_d = {}, {}, {}
for i = 1, n do
  s = io.read()
  local x, y, d = s:match("(%d+) (%d+) (%w)")
  x, y = tonumber(x), tonumber(y)
  raw_x[i], raw_y[i], raw_d[i] = x, y, d
  if d == "L" then
    ins(toleft, x, y)
  elseif d == "R" then
    ins(toright, x, y)
  elseif d == "U" then
    ins(toup, x, y)
  else
    ins(todown, x, y)
  end
end
sortall(toleft)
sortall(toright)
sortall(toup)
sortall(todown)

local ans = false
local function solvelb(tbl, z, mul)
  if tbl then
    local p = lower_bound(tbl, z) - 1
    if 0 < p then
      local v = (z - tbl[p]) * mul
      if not ans or v < ans then
        ans = v
      end
    end
  end
end

for i = 1, n do
  local x, y, d = raw_x[i], raw_y[i], raw_d[i]
  local xpy, xmy = x + y, x - y
  if d == "L" then
    --toLeft vs toRight
    solvelb(toright.y[y], x, 5)
    --toLeft vs toUp
    solvelb(toup.xmy[xmy], x, 10)
    --toLeft vs toDown
    solvelb(todown.xpy[xpy], x, 10)
  elseif d == "R" then
  elseif d == "U" then
    -- toUp vs toRight
    solvelb(toright.xpy[xpy], x, 10)
  else
    -- toDown vs toRight
    solvelb(toright.xmy[xmy], x, 10)
    -- toDown vs toUp
    solvelb(toup.x[x], y, 5)
  end
end
print(ans and ans or "SAFE")

Score: 600 points

Problem Statement

M-kun is a brilliant air traffic controller.

On the display of his radar, there are N airplanes numbered 1, 2, ..., N, all flying at the same altitude.

Each of the airplanes flies at a constant speed of 0.1 per second in a constant direction. The current coordinates of the airplane numbered i are (X_i, Y_i), and the direction of the airplane is as follows:

if U_i is U, it flies in the positive y direction;

if U_i is R, it flies in the positive x direction;

if U_i is D, it flies in the negative y direction;

if U_i is L, it flies in the negative x direction.

To help M-kun in his work, determine whether there is a pair of airplanes that will collide with each other if they keep flying as they are now.

If there is such a pair, find the number of seconds after which the first collision will happen.

We assume that the airplanes are negligibly small so that two airplanes only collide when they reach the same coordinates simultaneously.

Constraints

1 \leq N \leq 200000

0 \leq X_i, Y_i \leq 200000

U_i is U, R, D, or L.

The current positions of the N airplanes, (X_i, Y_i), are all distinct.

N, X_i, and Y_i are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 U_1
X_2 Y_2 U_2
X_3 Y_3 U_3
:
X_N Y_N U_N

Output

If there is a pair of airplanes that will collide with each other if they keep flying as they are now, print an integer representing the number of seconds after which the first collision will happen.

If there is no such pair, print SAFE.

Sample Input 1

2
11 1 U
11 47 D

Sample Output 1

230

If the airplanes keep flying as they are now, two airplanes numbered 1 and 2 will reach the coordinates (11, 24) simultaneously and collide.

Sample Input 2

4
20 30 U
30 20 R
20 10 D
10 20 L

Sample Output 2

SAFE

No pair of airplanes will collide.

Sample Input 3

8
168 224 U
130 175 R
111 198 D
121 188 L
201 116 U
112 121 R
145 239 D
185 107 L

Sample Output 3

100


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(dimensi0n, default_val) assert(type(default_val) ~= 'table') local n=dimensi0n 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 DBG = false
local insert = table.insert
local min = math.min
local sort = table.sort
local function getkeys(t)
    local keys = {}
    for k,v in pairs(t) do
        insert(keys, k)
    end
    sort(keys)
    return keys
end

local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end
--
local N = read.nl()
local X, Y, U = {},{},{}
local yy = {}
local xx = {}
local rr = {} -- right down
local ll = {} -- left down
local function push(tt, p, e)
    if not tt[p] then
        tt[p] = {}
    end
    insert(tt[p], e)
end
for i=1,N do
    X[i], Y[i], U[i] = read.nnl()
    U[i] = U[i]:sub(2,2)
    local e = i
    push(yy, Y[i], e)
    push(xx, X[i], e)
    local rrp = X[i] + Y[i]
    push(rr, rrp, e)
    local llp = X[i] - Y[i]
    push(ll, llp, e)
end
--richtraceback()
local INF = 10^18
local nearest_crash = INF
local function f1(name, tt, ttk, inv, fw, bk, sp)
    for _,w in ipairs(ttk) do
        local t = tt[w]
        dbgpr("on same " .. name , w)
        local inttk = {}
        for _,i in ipairs(t) do
            if U[i] == fw or U[i] == bk then
                insert(inttk, {inv[i], i, U[i]})
            end
        end
        sort(inttk, function (a1, a2)
            return a1[1] < a2[1]
        end)
        local state = 0
        local recentfwinv = -200000
        for _,ee in ipairs(inttk) do
            local i = ee[2]
            if U[i] == fw or U[i] == bk then
                dbgpr("plane #" .. i, "inv="..inv[i], "X="..X[i], "Y="..Y[i], U[i])
                if state == 0 then
                    if U[i] == fw then
                        state = 1
                        recentfwinv = inv[i]
                    end
                elseif state == 1 then
                    if U[i] == fw then
                        recentfwinv = inv[i]
                    elseif U[i] == bk then
                        local d = inv[i] - recentfwinv
                        nearest_crash = min(nearest_crash, d * sp)
                        dbgpr("crash!", i, nearest_crash)
                    end
                end
            end
        end
    end

end
f1('Y', yy, getkeys(yy), X, 'R', 'L', 5)
f1('X', xx, getkeys(xx), Y, 'U', 'D', 5)
local rrk = getkeys(rr)
f1('rr', rr, rrk, X, 'R', 'U', 10)
f1('rr', rr, rrk, X, 'D', 'L', 10)
local llk = getkeys(ll)
f1('ll', ll, llk, X, 'U', 'L', 10)
f1('ll', ll, llk, X, 'R', 'D', 10)

if nearest_crash == INF then
    print("SAFE")
else
    print(nearest_crash)
end

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

Submitted source-code file size, in bytes.

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

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


local 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(dimensi0n, default_val) assert(type(default_val) ~= 'table') local n=dimensi0n 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 DBG = false
local insert = table.insert
local function getkeys(t)
    local keys = {}
    for k,v in pairs(t) do
        insert(keys, k)
    end
    table.sort(keys)
    return keys
end

local function dbgpr(...)
    if DBG then
        io.write("[dbg]")
        print(...)
    end
end
--
local N = read.nl()
local X, Y, U = {},{},{}
local yy = {}
local xx = {}
local rr = {} -- right down
local ll = {} -- left down
local function push(tt, p, e)
    if not tt[p] then
        tt[p] = {}
    end
    insert(tt[p], e)
end
for i=1,N do
    X[i], Y[i], U[i] = read.nnl()
    U[i] = U[i]:sub(2,2)
    local e = i
    push(yy, Y[i], e)
    push(xx, X[i], e)
    local rrp = X[i] + Y[i]
    push(rr, rrp, e)
    local llp = X[i] - Y[i]
    push(ll, llp, e)
end
--richtraceback()
local INF = 10^18
local nearest_crash = INF
local function f1(name, tt, inv, fw, bk, sp)
    local ttk = getkeys(tt)
    for _,w in ipairs(ttk) do
        local t = tt[w]
        dbgpr("on same " .. name , w)
        local inttk = {}
        for _,i in ipairs(t) do
            if U[i] == fw or U[i] == bk then
                insert(inttk, {inv[i], i, U[i]})
            end
        end
        table.sort(inttk, function (a1, a2)
            return a1[1] < a2[1]
        end)
        local state = 0
        local recentfwinv = -200000
        for _,ee in ipairs(inttk) do
            local i = ee[2]
            if U[i] == fw or U[i] == bk then
                dbgpr("plane #" .. i, "inv="..inv[i], "X="..X[i], "Y="..Y[i], U[i])
                if state == 0 then
                    if U[i] == fw then
                        state = 1
                        recentfwinv = inv[i]
                    end
                elseif state == 1 then
                    if U[i] == fw then
                        recentfwinv = inv[i]
                    elseif U[i] == bk then
                        local d = inv[i] - recentfwinv
                        nearest_crash = math.min(nearest_crash, d * sp)
                        dbgpr("crash!", i, nearest_crash)
                    end
                end
            end
        end
    end

end
f1('Y', yy, X, 'R', 'L', 5)
f1('X', xx, Y, 'U', 'D', 5)
f1('rr', rr, X, 'R', 'U', 10)
f1('rr', rr, X, 'D', 'L', 10)
f1('ll', ll, X, 'U', 'L', 10)
f1('ll', ll, X, 'R', 'D', 10)

if nearest_crash == INF then
    print("SAFE")
else
    print(nearest_crash)
end


local L, R, d = io.read("*n", "*n", "*n")
local floor = math.floor

print(floor(R / d) - floor((L - 1) / d))

Score : 100 points

Problem Statement

How many multiples of d are there among the integers between L and R (inclusive)?

Constraints

All values in input are integers.

1 \leq L \leq R \leq 100

1 \leq d \leq 100

Input

Input is given from Standard Input in the following format:

L R d

Output

Print the number of multiples of d among the integers between L and R (inclusive).

Sample Input 1

5 10 2

Sample Output 1

3

Among the integers between 5 and 10, there are three multiples of 2: 6, 8, and 10.

Sample Input 2

6 20 7

Sample Output 2

2

Among the integers between 6 and 20, there are two multiples of 7: 7 and 14.

Sample Input 3

1 100 1

Sample Output 3

100


local read = io.read

local N = read("*n")

local out = 0
for i = 1, N do
	local a_element = read("*n")
	if i % 2 == 1 and a_element % 2 == 1 then
		out = out +1
	end
end

print(out)

Score : 200 points

Problem Statement

We have N squares assigned the numbers 1,2,3,\ldots,N. Each square has an integer written on it, and the integer written on Square i is a_i.

How many squares i satisfy both of the following conditions?

The assigned number, i, is odd.

The written integer is odd.

Constraints

All values in input are integers.

1 \leq N, a_i \leq 100

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \cdots a_N

Output

Print the number of squares that satisfy both of the conditions.

Sample Input 1

5
1 3 4 5 7

Sample Output 1

2

Two squares, Square 1 and 5, satisfy both of the conditions.

For Square 2 and 4, the assigned numbers are not odd.

For Square 3, the written integer is not odd.

Sample Input 2

15
13 76 46 15 50 98 93 77 31 43 84 90 6 24 14

Sample Output 2

3


n = io.read("*n")
for k = 1, n do
  cnt = 0
  for x = 1, math.floor(math.sqrt(k / 6)) do
    for y = 1, x do
      for z = 1, y do
        if (x * x + y * y + z * z + x * y + x * z + y * z) == k then
          if x == y and y == z then
            cnt = cnt + 1
          elseif (x == y and y ~= z) or (x == z and x ~=y) or(y == z and y ~= x) then
            cnt = cnt + 3
          elseif (x ~= y and x ~= z and y ~= z) then
            cnt = cnt + 3
          end
        end
      end
    end
  end
  print(cnt)
end

Score : 300 points

Problem Statement

Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:

1 \leq x,y,z

x^2 + y^2 + z^2 + xy + yz + zx = n

Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).

Constraints

All values in input are integers.

1 \leq N \leq 10^4

Input

Input is given from Standard Input in the following format:

N

Output

Print N lines. The i-th line should contain the value f(i).

Sample Input 1

20

Sample Output 1

0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0

For n=6, only (1,1,1) satisfies both of the conditions. Thus, f(6) = 1.

For n=11, three triples, (1,1,2), (1,2,1), and (2,1,1), satisfy both of the conditions. Thus, f(6) = 3.

For n=17, three triples, (1,2,2), (2,1,2), and (2,2,1), satisfy both of the conditions. Thus, f(17) = 3.

For n=18, three triples, (1,1,3), (1,3,1), and (3,1,1), satisfy both of the conditions. Thus, f(18) = 3.


-- 答え参照
local function xyz(x, y, z)
	return x*x + y*y + z*z + x*y + y*z + z*x
end

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

local loop_num = math.ceil(math.sqrt(N))

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

for x = 1, loop_num do
	for y = 1, loop_num do
		for z = 1, loop_num do
			local result = xyz(x, y, z)
			if result <= N then
				out_s[result] = out_s[result] + 1
			end
		end
	end
end

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


local r_shift = bit.rshift
local b_and = bit.band

local N = io.read("*n", "*l")
local X = io.read("*l")
local b_0 = string.byte("0")
local X_s = {}
local popcountX = 0
for i = 1, N do
	local byte = X:byte(i)
	if byte == b_0 then
		X_s[i] = 0
	else
		popcountX = popcountX + 1
		X_s[i] = 1
	end
end

local popcountXPlus1, popcountXMinus1 = popcountX + 1, popcountX - 1
--- 2^i%(Xの1の数+1)の配列(i=1,2,3,...,N)
local pow2ModPopcountXPlus1 = {}
pow2ModPopcountXPlus1[1] = 1
for i = 2, N do
	pow2ModPopcountXPlus1[i] = (pow2ModPopcountXPlus1[i-1] * 2) % popcountXPlus1
end
--- 2^i%(Xの1の数-1)の配列(i=1,2,3,...,N)
local pow2ModPopcountXMinus1 = {}
pow2ModPopcountXMinus1[1] = 1
if popcountXMinus1 > 0 then
	for i = 2, N do
		pow2ModPopcountXMinus1[i] = (pow2ModPopcountXMinus1[i-1] * 2) % popcountXMinus1
	end
end

--- X%(Xの1の数+1)
local xModPopcountXPlus1 = 0
for digit = 1, N do
	local pos = N + 1 - digit
	-- あらかじめ計算しておいた桁ごとの余りを利用してX%(Xの1の数+1)を求めていく
	if X_s[pos] == 1 then
		xModPopcountXPlus1 = xModPopcountXPlus1 + pow2ModPopcountXPlus1[digit]
		xModPopcountXPlus1 = xModPopcountXPlus1 % popcountXPlus1
	end
end
--- X%(Xの1の数-1)
local xModPopcountXMinus1 = 0
-- (Xの1の数-1)は0,-1の可能性があるからその排除
if popcountXMinus1 > 0 then
	for digit = 1, N do
		local pos = N + 1 - digit
		if X_s[pos] == 1 then
			xModPopcountXMinus1 = xModPopcountXMinus1 + pow2ModPopcountXMinus1[digit]
			xModPopcountXMinus1 = xModPopcountXMinus1 + popcountXMinus1
		end
	end
end

local function popcount(num)
	local count = 0
	while num > 0 do
		if b_and(num, 1) == 1 then
			count = count + 1
		end
		num = r_shift(num, 1)
	end
	return count
end

--- メモ化の配列
local f = {}
local function getF(num)
	if num == 0 then
		return 0
	end
	if f[num] and f[num] > 0 then
		return f[num]
	end
	local ans = 1 + getF(num % popcount(num))
	f[num] = ans
	return ans
end

for pos = 1, N do
	local digit = N + 1 - pos

	--- (Xの左からi桁目の01を反転した値)%(Xの1の数+-1)
	local modXi = 0
	if X_s[pos] == 0 then
		modXi = xModPopcountXPlus1 + pow2ModPopcountXPlus1[digit]
		modXi = modXi % popcountXPlus1
		local ans = 1 + getF(modXi)
		print(ans)
	elseif popcountXMinus1 > 0 then
		-- +popcountXMinus1はあまりをだすときにmodXiが負にならないようにする
		modXi = xModPopcountXMinus1 + (popcountXMinus1 - pow2ModPopcountXMinus1[digit])
		modXi = modXi % popcountXMinus1
		local ans = 1 + getF(modXi)
		print(ans)
	else
		print(0)
	end
end

Score : 400 points

Problem Statement

Let \mathrm{popcount}(n) be the number of 1s in the binary representation of n.
For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.

Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n is divided by \mathrm{popcount}(n)." (It can be proved that, under the constraints of this problem, n always becomes 0 after a finite number of operations.)

For example, when n=7, it becomes 0 after two operations, as follows:

\mathrm{popcount}(7)=3, so we divide 7 by 3 and replace it with the remainder, 1.

\mathrm{popcount}(1)=1, so we divide 1 by 1 and replace it with the remainder, 0.

You are given an integer X with N digits in binary.
For each integer i such that 1 \leq i \leq N, let X_i be what X becomes when the i-th bit from the top is inverted.
Find f(X_1), f(X_2), \ldots, f(X_N).

Constraints

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

X is an integer with N digits in binary, possibly with leading zeros.

Input

Input is given from Standard Input in the following format:

N
X

Output

Print N lines. The i-th line should contain the value f(X_i).

Sample Input 1

3
011

Sample Output 1

2
1
1

X_1 = 7, which will change as follows: 7 \rightarrow 1 \rightarrow 0. Thus, f(7) = 2.

X_2 = 1, which will change as follows: 1 \rightarrow 0. Thus, f(1) = 1.

X_3 = 2, which will change as follows: 2 \rightarrow 0. Thus, f(2) = 1.

Sample Input 2

23
00110111001011011001110

Sample Output 2

2
1
2
2
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
3


local r_shift = bit.rshift
local b_and = bit.band

local N = io.read("*n", "*l")
local X = io.read("*l")
local b_0 = string.byte("0")
local X_s = {}
local popcountX = 0
for i = 1, N do
	local byte = X:byte(i)
	if byte == b_0 then
		X_s[i] = 0
	else
		popcountX = popcountX + 1
		X_s[i] = 1
	end
end

local popcountXPlus1, popcountXMinus1 = popcountX + 1, popcountX - 1

local pow2ModPopcountXPlus1 = {}
pow2ModPopcountXPlus1[1] = 1
for i = 2, N do --ここ謎
	pow2ModPopcountXPlus1[i] = (pow2ModPopcountXPlus1[i-1] * 2) % popcountXPlus1
end
local pow2ModPopcountXMinus1 = {}
pow2ModPopcountXMinus1[1] = 1
if popcountXMinus1 > 0 then
	for i = 2, N do
		pow2ModPopcountXMinus1[i] = (pow2ModPopcountXMinus1[i-1] * 2) % popcountXMinus1
	end
end

local xModPopcountXPlus1 = 0
for digit = 1, N do
	local pos = N + 1 - digit
	if X_s[pos] == 1 then
		xModPopcountXPlus1 = xModPopcountXPlus1 + pow2ModPopcountXPlus1[digit]
		xModPopcountXPlus1 = xModPopcountXPlus1 % popcountXPlus1
	end
end
local xModPopcountXMinus1 = 0
if popcountXMinus1 > 0 then
	for digit = 1, N do
		local pos = N + 1 - digit
		if X_s[pos] == 1 then
			xModPopcountXMinus1 = xModPopcountXMinus1 + pow2ModPopcountXMinus1[digit]
			xModPopcountXMinus1 = xModPopcountXMinus1 + popcountXMinus1
		end
	end
end

local function popcount(num)
	local count = 0
	while num > 0 do
		if b_and(num, 1) == 1 then
			count = count + 1
		end
		num = r_shift(num, 1)
	end
	return count
end

local f = {}
local function getF(num)
	if num == 0 then
		return 0
	end
	if f[num] and f[num] > 0 then
		return f[num]
	end
	local ans = 1 + getF(num % popcount(num))
	f[num] = ans
	return ans
end

for pos = 1, N do
	local digit = N + 1 - pos

	local modXi = 0
	if X_s[pos] == 0 then
		modXi = xModPopcountXPlus1 + pow2ModPopcountXPlus1[digit]
		modXi = modXi % popcountXPlus1
		local ans = 1 + getF(modXi)
		print(ans)
	elseif popcountXMinus1 > 0 then
		modXi = xModPopcountXMinus1 + (popcountXMinus1 - pow2ModPopcountXMinus1[digit])
		modXi = modXi % popcountXMinus1
		local ans = 1 + getF(modXi)
		print(ans)
	else
		print(0)
	end
end


local mfl, mce = math.floor, math.ceil
local n = io.read("*n", "*l")
local t = {}
local s = io.read()
local cnt1 = 0
for i = 1, n do
  t[i] = s:byte(i) == 49
  if t[i] then cnt1 = cnt1 + 1 end
end
local plusmap, minusmap = {}, {}
for i = 1, n do
  plusmap[i], minusmap[i] = 0, 0
end
do
  local dv = cnt1 + 1
  local mul = 1
  for i = n, 1, -1 do
    plusmap[i] = mul
    mul = (mul * 2) % dv
  end
end
if 2 < cnt1 then
  local dv = cnt1 - 1
  local mul = 1
  for i = n, 1, -1 do
    minusmap[i] = mul
    mul = (mul * 2) % dv
  end
end
local plus = 0
do
  local dv = cnt1 + 1
  for i = 1, n do
    if t[i] then
      plus = (plus + plusmap[i]) % dv
    end
  end
end
local minus = 0
if 1 < cnt1 then
  local dv = cnt1 - 1
  for i = 1, n do
    if t[i] then
      minus = (minus + minusmap[i]) % dv
    end
  end
end

local function firstdevide(p, dv)
  if t[p] then
    local currem = minus
    currem = (currem + dv - minusmap[p]) % dv
    return currem
  else
    local currem = plus
    currem = (currem + plusmap[p]) % dv
    return currem
  end
end

local function getpopcnt(x)
  local c = 0
  while 0 < x do
    if x % 2 == 1 then c = c + 1 end
    x = mfl(x / 2)
  end
  return c
end

for iq = 1, n do
  local dv = t[iq] and cnt1 - 1 or cnt1 + 1
  if dv == 0 then
    print(0)
  else
    local rem = firstdevide(iq, dv)
    local cnt = 1
    while 0 < rem do
      dv = getpopcnt(rem)
      rem = rem % dv
      cnt = cnt + 1
    end
    print(cnt)
  end
end


local mfl, mce = math.floor, math.ceil
local n = io.read("*n", "*l")
local t = {}
local s = io.read()
local cnt1 = 0
for i = 1, n do
  t[i] = s:byte(i) == 49
  if t[i] then cnt1 = cnt1 + 1 end
end

local function firstdevide(p, dv)
  local currem = 0
  for i = 1, n do
    currem = currem * 2
    if i == p then
      if not t[i] then
        currem = currem + 1
      end
    else
      if t[i] then
        currem = currem + 1
      end
    end
    currem = currem % dv
  end
  return currem
end

local function getpopcnt(x)
  local c = 0
  while 0 < x do
    if x % 2 == 1 then c = c + 1 end
    x = mfl(x / 2)
  end
  return c
end

for iq = 1, n do
  local dv = t[iq] and cnt1 - 1 or cnt1 + 1
  local rem = firstdevide(iq, dv)
  local cnt = 1
  while 0 < rem do
    dv = getpopcnt(rem)
    rem = rem % dv
    cnt = cnt + 1
  end
  print(cnt)
end


local length = io.read()
local data = {AC = 0, WA = 0, TLE =0, RE = 0}

for i = 1, length do
    local key = io.read()
    if data[key] then
        data[key] = data[key] + 1
    end
end

print("AC X".." "..data["AC"])
print("WA X".." "..data["WA"])
print("TLE X".." "..data["TLE"])
print("RE X".." "..data["RE"])

Score : 200 points

Problem Statement

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.

See the Output section for the output format.

Constraints

1 \leq N \leq 10^5

S_i is AC, WA, TLE, or RE.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Sample Input 1

6
AC
TLE
AC
AC
WA
TLE

Sample Output 1

AC x 3
WA x 1
TLE x 2
RE x 0

We have 3, 1, 2, and 0 test case(s) for which the verdict is AC, WA, TLE, and RE, respectively.

Sample Input 2

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Sample Output 2

AC x 10
WA x 0
TLE x 0
RE x 0


local length = io.read()
local data = {AC = 0, WA = 0, TLE =0, RE = 0}

for i = 1, length do
    local key = io.read()
    if data[key] then
        data[key] = data[key] + 1
    end
end

for key, num in pairs(data) do
    print(key.." ".."X".." "..num)
end


n = io.read("*n", "*l")
t = {}
t.AC = 0
t.WA = 0
t.TLE = 0
t.RE = 0
for i = 1, n do
  s = io.read()
  t[s] = t[s] + 1
end
print("AC x " .. t.AC)
print("WA x " .. t.WA)
print("TLE x " .. t.TLE)
print("RE x " .. t.RE)


local h, w, k = io.read("*n", "*n", "*n", "*l")
local t = {}
for i = 1, h do
  t[i] = {}
  local s = io.read()
  for j = 1, w do
    t[i][j] = s:sub(j, j) == "#"
  end
end
local tot = 1 << (h + w)
local hflag, wflag = {}, {}
local ans = 0
for i = 0, tot - 1 do
  local ti = i
  for j = 1, h do
    hflag[j] = ti % 2 == 0
    ti = ti // 2
  end
  for j = 1, w do
    wflag[j] = ti % 2 == 0
    ti = ti // 2
  end
  local c = 0
  for j = 1, h do
    for k = 1, w do
      if t[j][k] and hflag[j] and wflag[k] then
        c = c + 1
      end
    end
  end
  if c == k then ans = ans + 1 end
end
print(ans)

Score : 300 points

Problem Statement

We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is ., and black if c_{i,j} is #.

Consider doing the following operation:

Choose some number of rows (possibly zero), and some number of columns (possibly zero). Then, paint red all squares in the chosen rows and all squares in the chosen columns.

You are given a positive integer K. How many choices of rows and columns result in exactly K black squares remaining after the operation? Here, we consider two choices different when there is a row or column chosen in only one of those choices.

Constraints

1 \leq H, W \leq 6

1 \leq K \leq HW

c_{i,j} is . or #.

Input

Input is given from Standard Input in the following format:

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

Output

Print an integer representing the number of choices of rows and columns satisfying the condition.

Sample Input 1

2 3 2
..#
###

Sample Output 1

5

Five choices below satisfy the condition.

The 1-st row and 1-st column

The 1-st row and 2-nd column

The 1-st row and 3-rd column

The 1-st and 2-nd column

The 3-rd column

Sample Input 2

2 3 4
..#
###

Sample Output 2

1

One choice, which is choosing nothing, satisfies the condition.

Sample Input 3

2 2 3
##
##

Sample Output 3

0

Sample Input 4

6 6 8
..##..
.#..#.
#....#
######
#....#
#....#

Sample Output 4

208


local n = io.read("*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
table.sort(a, function(x, y) return x > y end)
local ans = a[1]
for i = 2, n - 1 do
  local p = 1 + (i // 2)
  ans = ans + a[p]
end
print(ans)

Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6


local n,k=io.read("n","n")
local a={}
for i=1,n do
    a[i]=io.read("n")
end
table.sort(a)
local mod=1000000007
local mul1=1
for i=1,k do
    mul1=mul1*(a[i]<0 and -a[i] or a[i])%mod
end
local mul2=1
for i=n,n-k+1,-1 do
    mul2=mul2*(a[i]<0 and -a[i] or a[i])%mod
end
print(math.max(mul1,mul2))

Score : 500 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.

Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Constraints

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

|A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 \ldots A_N

Output

Print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Sample Input 1

4 2
1 2 -3 -4

Sample Output 1

12

The possible products of the two chosen elements are 2, -3, -4, -6, -8, and 12, so the maximum product is 12.

Sample Input 2

4 3
-1 -2 -3 -4

Sample Output 2

1000000001

The possible products of the three chosen elements are -24, -12, -8, and -6, so the maximum product is -6.

We print this value modulo (10^9+7), that is, 1000000001.

Sample Input 3

2 1
-1 1000000000

Sample Output 3

1000000000

The possible products of the one chosen element are -1 and 1000000000, so the maximum product is 1000000000.

Sample Input 4

10 10
1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1

Sample Output 4

999983200

Be sure to print the product modulo (10^9+7).


local n = io.read("*n")
local edge = {}
local z = 0
for i = 1, n do
  edge[i] = {}
  local v = (i * (i + 1)) // 2
  z = z + v
end
for i = 1, n - 1 do
  local a, b = io.read("*n", "*n")
  if b < a then a, b = b, a end
  z = z - a * (n + 1 - b)
end
print(z)

Score : 600 points

Problem Statement

We have a tree with N vertices and N-1 edges, respectively numbered 1, 2,\cdots, N and 1, 2, \cdots, N-1. Edge i connects Vertex u_i and v_i.

For integers L, R (1 \leq L \leq R \leq N), let us define a function f(L, R) as follows:

Let S be the set of the vertices numbered L through R. f(L, R) represents the number of connected components in the subgraph formed only from the vertex set S and the edges whose endpoints both belong to S.

Compute \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

Constraints

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

1 \leq u_i, v_i \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print \sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R).

Sample Input 1

3
1 3
2 3

Sample Output 1

7

We have six possible pairs (L, R) as follows:

For L = 1, R = 1, S = \{1\} and we have 1 connected component.

For L = 1, R = 2, S = \{1, 2\} and we have 2 connected components.

For L = 1, R = 3, S = \{1, 2, 3\} and we have 1 connected component, since S contains both endpoints of each of the edges 1, 2.

For L = 2, R = 2, S = \{2\} and we have 1 connected component.

For L = 2, R = 3, S = \{2, 3\} and we have 1 connected component, since S contains both endpoints of Edge 2.

For L = 3, R = 3, S = \{3\} and we have 1 connected component.

The sum of these is 7.

Sample Input 2

2
1 2

Sample Output 2

3

Sample Input 3

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

Sample Output 3

113


local a = io.read()
print(math.floor(a + a*a + a*a*a))

Score : 100 points

Problem Statement

Given an integer a as input, print the value a + a^2 + a^3.

Constraints

1 \leq a \leq 10

a is an integer.

Input

Input is given from Standard Input in the following format:

a

Output

Print the value a + a^2 + a^3 as an integer.

Sample Input 1

2

Sample Output 1

14

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110


local str = io.read()
str = str + str*str + str*str*str
str = math.floor(str)
print(str)


function rl()
   r = {}
   for word in io.read():gmatch("%S+") do
      table.insert(r, tonumber(word))
   end
   return r
end

a = rl()[1]

print(a + a*a + a*a*a)


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

print(a + a*a + a*a*a)


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

local count = 0
--[[ パターン1
for i = 1, S:len() do
	if S:sub(i, i) ~= T:sub(i, i) then
		count = count + 1
	end
end
--]]
---[[ パターン2
local S_byte_s, T_byte_s = {}, {T:byte(1, -1)}
for i = 1, S:len() do
	S_byte_s[i] = S:byte(i)
	T_byte_s[i] = T:byte(i)
end

for i = 1, S:len() do
	if S_byte_s[i] ~= T_byte_s[i] then
		count = count + 1
	end
end
--]]
print(count)

Score : 200 points

Problem Statement

Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.

Operation: Choose one character of S and replace it with a different character.

Constraints

S and T have lengths between 1 and 2\times 10^5 (inclusive).

S and T consists of lowercase English letters.

S and T have equal lengths.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the answer.

Sample Input 1

cupofcoffee
cupofhottea

Sample Output 1

4

We can achieve the objective in four operations, such as the following:

First, replace the sixth character c with h.

Second, replace the eighth character f with t.

Third, replace the ninth character f with t.

Fourth, replace the eleventh character e with a.

Sample Input 2

abcde
bcdea

Sample Output 2

5

Sample Input 3

apple
apple

Sample Output 3

0

No operations may be needed to achieve the objective.


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

local count = 0
--[[ パターン1
for i = 1, S:len() do
	if S:sub(i, i) ~= T:sub(i, i) then
		count = count + 1
	end
end
--]]
---[[ パターン2
local S_byte_s, T_byte_s = {S:byte(1, -1)}, {T:byte(1, -1)}
for i = 1, S:len() do
	if S_byte_s[i] ~= T_byte_s[i] then
		count = count + 1
	end
end
--]]
print(count)


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

local total=0
for i=1,k do
    total=total+p[i]
end
print(total)

Score : 200 points

Problem Statement

A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

1 \leq K \leq N \leq 1000

1 \leq p_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 \ldots p_N

Output

Print an integer representing the minimum possible total price of fruits.

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.

The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

Sample Input 2

1 1
1000

Sample Output 2

1000


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

table.sort(p)

local out = 0
for i = 1, K do
	out = out + p[i]
end

print(out)


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"
K=io.read"*n"
p=reada(N)
table.sort(p)
s=0
for i=1,K do
s=s+p[i]
end
print(s)


local t = {"a", "b", "c", "d", "e","f", "g", "h", "i","j", "k", "l", "m", "n","o", "p", "q", "r","s", "t ", "u", "v", "w","x", "y", "z"}
-- print(#t)
local N = io.read()
-- local N = 123456789
local x = string.byte("a") - 1
local aa = ""
local function a(N)
    local n = math.floor(N / 26)
    local m = N % 26
    if n == 0 and m == 0 then
        aa = aa..t[26]
        return
    end
    if n > 0 then
       a(n)
    else
        if m ~= 0 and n ~= 0 then
            aa = aa..t[n]
            return
        end
    end
    if m == 0 then
        aa = aa..t[26]
    else
        aa = aa..t[m]
    end
end
a(N)
print(aa)

Score : 300 points

Problem Statement

1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:

the dogs numbered 1,2,\cdots,26 were respectively given the names a, b, ..., z;

the dogs numbered 27,28,29,\cdots,701,702 were respectively given the names aa, ab, ac, ..., zy, zz;

the dogs numbered 703,704,705,\cdots,18277,18278 were respectively given the names aaa, aab, aac, ..., zzy, zzz;

the dogs numbered 18279,18280,18281,\cdots,475253,475254 were respectively given the names aaaa, aaab, aaac, ..., zzzy, zzzz;

the dogs numbered 475255,475256,\cdots were respectively given the names aaaaa, aaaab, ...;

and so on.

To sum it up, the dogs numbered 1, 2, \cdots were respectively given the following names:

a, b, ..., z, aa, ab, ..., az, ba, bb, ..., bz, ..., za, zb, ..., zz, aaa, aab, ..., aaz, aba, abb, ..., abz, ..., zzz, aaaa, ...

Now, Roger asks you:

"What is the name for the dog numbered N?"

Constraints

N is an integer.

1 \leq N \leq 1000000000000001

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer to Roger's question as a string consisting of lowercase English letters.

Sample Input 1

2

Sample Output 1

b

Sample Input 2

27

Sample Output 2

aa

Sample Input 3

123456789

Sample Output 3

jjddja


local t = {"a", "b", "c", "d", "e","f", "g", "h", "i","j", "k", "l", "m", "n","o", "p", "q", "r","s", "t ", "u", "v", "w","x", "y", "z"}
local N = io.read()
local x = string.byte("a") - 1
local aa = ""
local function a(N)
    local n = math.floor(N / 26)
    local m = N % 26
    if n > 26 then
       a(n)
    else
        if m ~= 0 then
            aa = aa..t[n]
        end
    end
    if m == 0 then
        aa = aa..t[26]
    else
        aa = aa..t[m]
    end
end
a(N)
print(aa)


local t = {"a", "b", "c", "d", "e","f", "g", "h", "i","j", "k", "l", "m", "n","o", "p", "q", "r","s", "t", "u", "v", "w","x", "y", "z"}

local N = io.read()
local x = string.byte("a") - 1
local aa = ""
local function a(N)
    local n = math.floor(N/26)
    local m = N % 26
    if n > 26 then
       a(n)
    else
        aa = aa..t[n]
    end
    aa = aa..t[m]
end
a(N)
print(aa)


--https://www.lua.org/pil/11.4.html
local List = {}
function List.new ()
  return {first = 0, last = -1}
end

function List.pushleft (list, value)
  local first = list.first - 1
  list.first = first
  list[first] = value
end

function List.pushright (list, value)
  local last = list.last + 1
  list.last = last
  list[last] = value
end

function List.popleft (list)
  local first = list.first
  if first > list.last then return false end
  local value = list[first]
  list[first] = nil
  list.first = first + 1
  return value
end

function List.popright (list)
  local last = list.last
  if list.first > last then return false end
  local value = list[last]
  list[last] = nil
  list.last = last - 1
  return value
end

----------

local n=io.read("n")
local que=List.new()

local ts=26
while n>0 do
    List.pushleft(que,n%ts)
    n=n//26
end

local answer={}
while true do
    local pop=List.popleft(que)
    if not pop then
        break
    end
    table.insert(answer,string.char(pop+96))
end
print(table.concat(answer,""))


N=io.read"*n"
i=1
s=0
while true do
	s=s+math.floor(26^i+.5)
	if(N<s)then break end
	i=i+1
end
s=N-s+math.floor(26^i+.5)-1
if(s<0)then i=i-1 s=math.floor(26^i+.5)-1 end
r={}
ab=string.byte"a"
for j=1,i do
	r[i-j+1]=string.char(ab+s%26)
	s=(s-s%26)/26
end
print(table.concat(r))


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

local q=io.read("n")
for i=1,q do
    local b,c=io.read("n","n")
    if a[b] then
        sum=sum+a[b]*c-a[b]*b
        a[c]=(a[c] or 0)+a[b]
        print(sum)
    else
        print(sum)
    end
end

Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}

B_{i} \neq C_{i}

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

Sample Input 1

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

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

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

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000


local n = io.read("*n")
local t = {}
for i = 1, 100000 do
  t[i] = 0
end
for i = 1, n do
  local a = io.read("*n")
  t[a] = t[a] + 1
end
local ret = 0
for i = 1, 100000 do
  ret = ret + t[i] * i
end
local q = io.read("*n")
for iq = 1, q do
  local b, c = io.read("*n", "*n")
  ret = ret + (c - b) * t[b]
  print(ret)
  t[c] = t[c] + t[b]
  t[b] = 0
end


local function getgcd(x, y)
  while 0 < x do
    x, y = y % x, x
  end
  return y
end
z = io.read("*n")
gcd = getgcd(z, 360)
print(360 // gcd)

Score : 200 points

Problem Statement

Takahashi is standing on a two-dimensional plane, facing north. Find the minimum positive integer K such that Takahashi will be at the starting position again after he does the following action K times:

Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise.

Constraints

1 \leq X \leq 179

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of times Takahashi will do the action before he is at the starting position again.

Sample Input 1

90

Sample Output 1

4

Takahashi's path is a square.

Sample Input 2

1

Sample Output 2

360


local mod = 998244353
local function badd(x, y) return (x + y) % mod end
local function bmul(x, y) return (x * y) % mod end
local a, b = io.read("*n", "*n")
local c, d = io.read("*n", "*n")
local dp = {}
for i = 1, c do
  dp[i] = {}
  for j = 1, d do
    dp[i][j] = 0
  end
end
dp[a][b] = 1
for ia = a, c do
  for ib = b, d do
    if ia == a then
      if ib == b then
      else
        dp[a][ib] = bmul(dp[a][ib - 1], a)
      end
    elseif ib == b then
      dp[ia][b] = bmul(dp[ia - 1][b], b)
    else
      local v1 = bmul(dp[ia][ib - 1], ia)
      local v2 = bmul(dp[ia - 1][ib], ib)
      local v3 = bmul(dp[ia - 1][ib - 1], bmul(ia - 1, ib - 1))
      v3 = mod - v3
      dp[ia][ib] = badd(v1, badd(v2, v3))
    end
  end
end
print(dp[c][d])

Score : 600 points

Problem Statement

We have a grid with A horizontal rows and B vertical columns, with the squares painted white. On this grid, we will repeatedly apply the following operation:

Assume that the grid currently has a horizontal rows and b vertical columns. Choose "vertical" or "horizontal".

If we choose "vertical", insert one row at the top of the grid, resulting in an (a+1) \times b grid.

If we choose "horizontal", insert one column at the right end of the grid, resulting in an a \times (b+1) grid.

Then, paint one of the added squares black, and the other squares white.

Assume the grid eventually has C horizontal rows and D vertical columns. Find the number of ways in which the squares can be painted in the end, modulo 998244353.

Constraints

1 \leq A \leq C \leq 3000

1 \leq B \leq D \leq 3000

A, B, C, and D are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of ways in which the squares can be painted in the end, modulo 998244353.

Sample Input 1

1 1 2 2

Sample Output 1

3

Any two of the three squares other than the bottom-left square can be painted black.

Sample Input 2

2 1 3 4

Sample Output 2

65

Sample Input 3

31 41 59 265

Sample Output 3

387222020


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 X, Y = read.nn()
local k2 = Y - 2*X
if k2 % 2 == 1 or k2 < 0 then
    print("No")
    return
end
local t2 = 4*X - Y
if t2 % 2 == 1 or t2 < 0 then
    print("No")
    return
end
print("Yes")

Score : 200 points

Problem Statement

There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.

Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.

Constraints

1 \leq X \leq 100

1 \leq Y \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If there is a combination of numbers of cranes and turtles in which the statement is correct, print Yes; otherwise, print No.

Sample Input 1

3 8

Sample Output 1

Yes

The statement "there are 3 animals in total in the garden, and they have 8 legs in total" is correct if there are two cranes and one turtle. Thus, there is a combination of numbers of cranes and turtles in which the statement is correct.

Sample Input 2

2 100

Sample Output 2

No

There is no combination of numbers of cranes and turtles in which this statement is correct.

Sample Input 3

1 2

Sample Output 3

Yes

We also consider the case in which there are only cranes or only turtles.


local read = io.read
local insert = table.insert
local abs = math.abs

local X, N = read("*n", "*n")
local p = {}
for i = 1, N do
	p[i] = read("*n")
end

local not_p = {}
for i = 1, 100 do
	local can_ins = true
	for j = 1, N do
		if p[j] == i then
			can_ins = false
			break
		end
	end
	if can_ins then
		insert(not_p, i)
	end
end

local out = math.huge
for i = 1, #not_p do
	if abs(not_p[i] - X) < abs(out - X) then
		out = not_p[i]
	end
end

print(out)

Score : 300 points

Problem Statement

Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.

Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, report the smallest such integer.

Constraints

1 \leq X \leq 100

0 \leq N \leq 100

1 \leq p_i \leq 100

p_1, \ldots, p_N are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X N
p_1 ... p_N

Output

Print the answer.

Sample Input 1

6 5
4 7 10 6 5

Sample Output 1

8

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the one nearest to 6 is 8.

Sample Input 2

10 5
4 7 10 6 5

Sample Output 2

9

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the ones nearest to 10 are 9 and 11. We should print the smaller one, 9.

Sample Input 3

100 0

Sample Output 3

100

When N = 0, the second line in the input will be empty. Also, as seen here, X itself can be the answer.


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 X, N = read.nn()
local P = {}
for i=1,N do
    P[read.n()] = true
end
local ans = -1
local best = math.abs(ans - X)
for i=0,101 do
    if P[i] then
    else
        if math.abs(i - X) < best then
            ans = i
            best = math.abs(i - X)
        end
    end
end
print(ans)


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
local function array(dimension, default_val) 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 X, N = read.nn()
local P = {}
for i=1,N do
    P[read.n()] = true
end
local ans = -1
local best = 1000
for i=0,100 do
    if P[i] then
    else
        if math.abs(i - X) < best then
            ans = i
            best = math.abs(i - X)
        end
    end
end
print(ans)


local a,v=io.read("n","n")
local b,w=io.read("n","n")
local t=io.read("n")

if a<b then
    if a+v*t>=b+w*t then
        print("YES")
    else
        print("NO")
    end
else
    if a-v*t<=b-w*t then
        print("YES")
    else
        print("NO")
    end
end

Score : 200 points

Problem Statement

Two children are playing tag on a number line. (In the game of tag, the child called "it" tries to catch the other child.) The child who is "it" is now at coordinate A, and he can travel the distance of V per second.
The other child is now at coordinate B, and she can travel the distance of W per second.

He can catch her when his coordinate is the same as hers.
Determine whether he can catch her within T seconds (including exactly T seconds later).
We assume that both children move optimally.

Constraints

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

1 \leq V,W \leq 10^9

1 \leq T \leq 10^9

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A V
B W
T

Output

If "it" can catch the other child, print YES; otherwise, print NO.

Sample Input 1

1 2
3 1
3

Sample Output 1

YES

Sample Input 2

1 2
3 2
3

Sample Output 2

NO

Sample Input 3

1 2
3 3
3

Sample Output 3

NO


local a,v=io.read("n","n")
local b,w=io.read("n","n")
local t=io.read("n")

if a<b then
    if a+v*t>=b+w*t then
        print("YES")
    else
        print("NO")
    end
else
    if a-v*t>=b-w*t then
        print("YES")
    else
        print("NO")
    end
end


local bls, brs = bit.lshift, bit.rshift
local mmi, mma = math.min, math.max
local bxor = bit.bxor

local function grayCode(x)
  return bxor(x, brs(x, 1))
end

-- add_func(idx), rm_func(idx), work_func()
local function grayWalk(size, add_func, rm_func, work_func)
  local prv = 0
  local total = bls(1, size) - 1
  local bpos = {}
  for i = 1, size do
    bpos[bls(1, i - 1)] = i
  end
  for i = 1, total do
    local v = grayCode(i)
    if prv < v then
      prv, v = v, v - prv
      add_func(bpos[v])
    else
      prv, v = v, prv - v
      rm_func(bpos[v])
    end
    work_func()
  end
end

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

local tgt = 0
local weight, val = 0, 0
local tbl = nil
local function add_func(idx)
  weight = weight + w[brs(tgt, idx - 1)]
  val = val + v[brs(tgt, idx - 1)]
end
local function rm_func(idx)
  weight = weight - w[brs(tgt, idx - 1)]
  val = val - v[brs(tgt, idx - 1)]
end
local function work_func()
  if weight <= ten5 then
    tbl[weight] = mma(tbl[weight], val)
  end
end

for i = 512, mmi(n, 1023) do
  tgt = i
  head_tbl[i - 511] = {}
  tbl = head_tbl[i - 511]
  for j = 1, ten5 do
    tbl[j] = 0
  end
  weight, val = 0, 0
  grayWalk(10, add_func, rm_func, work_func)
  for i = 2, ten5 do
    tbl[i] = mma(tbl[i], tbl[i - 1])
  end
end

local q = io.read("*n")
local ans, wlim = 0, 0
local function work_func2()
  if weight <= wlim then
    ans = mma(ans, val)
  end
end
local function work_func3()
  if weight <= wlim then
    ans = mma(ans, val)
  end
  if weight < wlim then
    ans = mma(ans, val + tbl[wlim - weight])
  end
end
for iq = 1, q do
  local pos, wlim_tmp = io.read("*n", "*n")
  wlim = wlim_tmp
  local deg = 0
  do
    local tmp = pos
    while 0 < tmp do
      deg, tmp = deg + 1, brs(tmp, 1)
    end
  end
  if pos < 512 then
    ans = 0
    weight, val = 0, 0
    tgt = pos
    grayWalk(deg, add_func, rm_func, work_func2)
    print(ans)
  elseif pos < 1024 then
    print(head_tbl[pos - 511][wlim])
  else
    deg = deg - 10
    tbl = head_tbl[brs(pos, deg) - 511]
    ans = tbl[wlim]
    weight, val = 0, 0
    tgt = pos
    grayWalk(deg, add_func, rm_func, work_func3)
    print(ans)
  end
end

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 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
  local klim, mul = 1, 2
  for j = 1, jlim do
    if j == mul then
      klim, mul = klim + 1, mul * 2
    end
    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())


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)
    for j = 1, 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
      if weight < wlim then
        ans = mma(ans, val + tbl[wlim - weight])
      end
    end
    output(ans)
  end
end
debug(os.clock())


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 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 = 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 n = io.read("*n")
local primes = getprimes(mce(msq(n)))
local dvp = getdivisorparts(n, primes)
local ret = 0
for i = 1, #dvp do
  local cnt = dvp[i].cnt
  local cur = 1
  while cur <= cnt do
    ret = ret + 1
    cnt = cnt - cur
    cur = cur + 1
  end
end
print(ret)

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, 1000000007
  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, 1000000007
  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
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

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, 2000000000
  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, 2000000001
  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 n = io.read("*n")
local t = {}
local imos = {}
for i = 1, n + 1 do
  t[i] = io.read("*n")
  imos[i] = 0
end
imos[n + 2] = 0
local rem = 1
local score = 0
local stage = 0
for i = 1, n + 1 do
  local v = t[i]
  while rem < v and stage < i do
    score = score + rem * (i - stage)
    imos[stage + 1] = imos[stage + 1] + rem
    imos[i] = imos[i] - rem
    stage = stage + 1
    v = v - rem
    rem = imos[stage]
    imos[stage + 1] = imos[stage + 1] + imos[stage]
  end
  if i <= stage then
    score = -1
    break
  end
  score = score + v * (i - stage)
  rem = rem - v
  imos[stage + 1] = imos[stage + 1] + v
  imos[i] = imos[i] - v
end
print(score)

Score : 600 points

Problem Statement

Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1.

Notes

A binary tree is a rooted tree such that each vertex has at most two direct children.

A leaf in a binary tree is a vertex with zero children.

The depth of a vertex v in a binary tree is the distance from the tree's root to v. (The root has the depth of 0.)

The depth of a binary tree is the maximum depth of a vertex in the tree.

Constraints

0 \leq N \leq 10^5

0 \leq A_i \leq 10^{8} (0 \leq i \leq N)

A_N \geq 1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 A_2 \cdots A_N

Output

Print the answer as an integer.

Sample Input 1

3
0 1 1 2

Sample Output 1

7

Below is the tree with the maximum possible number of vertices. It has seven vertices, so we should print 7.

Sample Input 2

4
0 0 1 0 2

Sample Output 2

10

Sample Input 3

2
0 3 1

Sample Output 3

-1

Sample Input 4

1
1 1

Sample Output 4

-1

Sample Input 5

10
0 0 1 1 2 3 5 8 13 21 34

Sample Output 5

264


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 = 1.0 * d * src
    if src <= 1000000000 then
      local z = cost + d * src
      if 0 < z then
        cand = mmi(cand, z)
      end
    end
    -- if 1 <= z then
    -- 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 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 z = cost + d * src
    if 1 <= z then
      cand = mmi(cand, z)
    end
    if src == 1 then
      if not cand then
        cand = cost + d
      else
        cand = mmi(cand, cost + d)
      end
    else
      -- 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


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[-1/k] then
        counter=counter-(iwashi[k]*iwashi[-1/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 = 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
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 zero = 0

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
    zero = zero + 1
  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
ret = bsub(ret, 1)
ret = badd(ret, zero)
print(ret)


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

print((S == T:sub(1, T:len() - 1)) 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