local mfl, mce = math.floor, math.ceil
local n, k = io.read("*n", "*n")
assert(-1000000000 <= k and k <= 1000000000)
local p, c = {}, {}
for i = 1, n do
  p[i] = io.read("*n")
end
for i = 1, n do
  c[i] = io.read("*n")
  assert(-1000000000 <= c[i] and c[i] <= 1000000000)
end
local asked = {}
for i = 1, n do
  asked[i] = false
end
local zpos = 1
local function findstart()
  for i = zpos, n do
    if not asked[i] then zpos = i + 1 return i end
  end
  return false
end
local ret = -1000000007LL
local function mma_l(a, b) return a < b and b or a end
while true do
  local spos = findstart()
  if not spos then break end
  local route = {spos}
  local sum = 0LL + c[spos]
  local src = spos
  asked[spos] = true
  while true do
    local dst = p[src]
    if asked[dst] then break end
    asked[dst] = true
    table.insert(route, dst)
    sum = sum + c[dst]
    src = dst
  end
  local len = #route
  if 0LL < sum then
    local lp = mfl(k / len)
    local rem = k - lp * len
    sum = sum * lp
    ret = mma_l(ret, sum)
    for i = 1, len do
      local v = 0LL
      local src = route[i]
      for j = 1, rem do
        local dst = p[src]
        v = v + c[dst]
        ret = mma_l(ret, sum + v)
        src = dst
      end
    end
  else
    for i = 1, len do
      local v = 0LL
      local src = route[i]
      local lim = math.min(len, k)
      for j = 1, lim do
        local dst = p[src]
        v = v + c[dst]
        ret = mma_l(ret, v)
        src = dst
      end
    end
  end
end
ret = tostring(ret):gsub("LL", "")
print(ret)

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

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

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


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 max = math.max

local R, C, K = read.nnn()
local item = array(1,0)
for i=1,K do
    local r,c,v = read.nnn()
    item[r*C + c] = v
end

local target1
local target2
local function chmax1(g,val)
    target1[g] = max(target1[g], val)
end
local function chmax2(g,val)
    target2[g] = max(target2[g], val)
end
local dp = array(2,0)

dp[1][0] = 0
dp[1][1] = item[1*C+1]
for r=1,R do
    for c=1,C do
        target1 = dp[c]
        target2 = dp[c+1]
        local rval = item[r*C+c+1]
        local dval = item[(r+1)*C+c]
        local cur0 = target1[0]
        local cur1 = target1[1]
        local cur2 = target1[2]
        local cur3 = target1[3]
        target1[0] = 0
        target1[1] = 0
        target1[2] = 0
        target1[3] = 0
        chmax1(1,cur0+dval)
        chmax1(0,cur0)
        chmax1(1,cur1+dval)
        chmax1(0,cur1)
        chmax1(1,cur2+dval)
        chmax1(0,cur2)
        chmax1(1,cur3+dval)
        chmax1(0,cur3)
        chmax2(0+1,cur0+rval)
        chmax2(0,cur0)
        chmax2(1+1,cur1+rval)
        chmax2(1,cur1)
        chmax2(2+1,cur2+rval)
        chmax2(2,cur2)
        chmax2(3+1,cur3+rval)
        chmax2(4,cur3)
    end
end
print(max(dp[C][0],dp[C][1],dp[C][2],dp[C][3]))

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

Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

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

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

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

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142

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 max = math.max

local R, C, K = read.nnn()
local item = array(2, 0)
for i=1,K do
    local r,c,v = read.nnn()
    item[r][c] = v
end

local dp,dp_next = array(2,0),array(2,0)
local function chmax1(c,g,val)
    dp[c][g] = max(dp[c][g], val)
end
local function chmax2(c,g,val)
    dp_next[c][g] = max(dp_next[c][g], val)
end

dp[1][0] = 0
dp[1][1] = item[1][1]
for r=1,R do
    for c=1,C do
        for g=0,3 do
            dp_next[c][g] = 0
        end
        for g=0,3 do
            local curval = dp[c][g]
            chmax1(c+1,g+1,curval+item[r][c+1])
            chmax1(c+1,g,curval)
            chmax2(c,1,curval+item[r+1][c])
            chmax2(c,0,curval)
        end
    end
    dp, dp_next = dp_next, dp
end
print(max(dp[C][0],dp[C][1],dp[C][2],dp[C][3]))


local mfl = math.floor
local TranFFT = {}

TranFFT.initialize = function(self)
  self.size = 19
  -- 2^19 = 524288
  self.n = 524288
  -- 40003698689: prime,
  -- 40003698689 % 524288 = 1
  self.mod = 40003698689
  -- (463881^524288) % mod = 1
  self.w = 463881
  -- (40003622388 * 524288) % mod = 1
  self.ninv = 40003622388
  -- (1547695164 * 463881) % mod = 1
  self.winv = 1547695164

  self.p2 = {1}
  for i = 2, self.size do
    self.p2[i] = self.p2[i - 1] * 2
  end
  self.binv = {}
  for i = 1, self.n do
    local y, z = 0, i - 1
    for j = 1, self.size do
      y = y + (z % 2) * self.p2[self.size + 1 - j]
      z = mfl(z / 2)
    end
    self.binv[i] = y + 1
  end
  self.wmul = {1}
  local w1 = self.w % 10000
  local w2 = mfl(self.w / 10000) % 10000
  local w3 = mfl(self.w / 100000000)
  for i = 2, self.n do
    self.wmul[i] = self:mul_predef(self.wmul[i - 1], w1, w2, w3)
  end
  self.winvmul = {1}
  w1 = self.winv % 10000
  w2 = mfl(self.winv / 10000) % 10000
  w3 = mfl(self.winv / 100000000)
  for i = 2, self.n do
    self.winvmul[i] = self:mul_predef(self.winvmul[i - 1], w1, w2, w3)
  end
end
TranFFT.add = function(self, x, y) return (x + y) % self.mod end

-- super slow multiply functions
TranFFT.mul = function(self, x, y)
  local mod = self.mod
  local x1, y1 = x % 10000, y % 10000
  local x2, y2 = mfl(x / 10000) % 10000, mfl(y / 10000) % 10000
  local x3, y3 = mfl(x / 100000000), mfl(y / 100000000)
  local ret = (x1 * y1 + (x1 * y2 + x2 * y1) * 10000) % mod
  ret = (ret + (x1 * y3 + x2 * y2 + x3 * y1) * 10000 % mod * 10000 % mod) % mod
  ret = (ret + (x2 * y3 + x3 * y2) * 10000 % mod * 10000 % mod * 10000) % mod
  ret = (ret +  x3 * y3 * 10000 % mod * 10000 % mod * 10000 % mod * 10000) % mod
  return ret
end

TranFFT.mul_predef = function(self, x, y1, y2, y3)
  local mod = self.mod
  local x1 = x % 10000
  local x2 = mfl(x / 10000) % 10000
  local x3 = mfl(x / 100000000)
  local ret = (x1 * y1 + (x1 * y2 + x2 * y1) * 10000) % mod
  ret = (ret + (x1 * y3 + x2 * y2 + x3 * y1) * 10000 % mod * 10000 % mod) % mod
  ret = (ret + (x2 * y3 + x3 * y2) * 10000 % mod * 10000 % mod * 10000) % mod
  ret = (ret +  x3 * y3 * 10000 % mod * 10000 % mod * 10000 % mod * 10000) % mod
  return ret
end

TranFFT.twice = function(self, x)
  local mod = self.mod
  local x1 = x % 10000
  local x2 = mfl(x / 10000) % 10000
  local x3 = mfl(x / 100000000)
  local ret = (x1 * x1 + (2 * x1 * x2) * 10000) % mod
  ret = (ret + (2 * x1 * x3 + x2 * x2) * 10000 % mod * 10000 % mod) % mod
  ret = (ret + (2 * x2 * x3) * 10000 % mod * 10000 % mod * 10000) % mod
  ret = (ret +  x3 * x3 * 10000 % mod * 10000 % mod * 10000 % mod * 10000) % mod
  return ret
end

TranFFT.fft_common = function(self, ary, wmul)
  local ret = {}
  for i = 1, self.n do
    ret[i] = ary[self.binv[i]]
  end
  for i = 1, self.size do
    local step_size = self.p2[i]
    local step_count = self.p2[self.size + 1 - i]
    for istep = 1, step_count do
      local ofst = (istep - 1) * step_size * 2
      for j = 1, step_size do
        local a1, a2 = ret[ofst + j], ret[ofst + step_size + j]
        ret[ofst + j] = self:add(a1, self:mul(a2, wmul[1 + (j - 1) * step_count]))
        ret[ofst + step_size + j] = self:add(a1, self:mul(a2, wmul[1 + (j + step_size - 1) * step_count]))
      end
    end
  end
  return ret
end

TranFFT.fft = function(self, ary)
  return self:fft_common(ary, self.wmul)
end
TranFFT.ifft = function(self, ary)
  local ret = self:fft_common(ary, self.winvmul)
  for i = 1, self.n do
    ret[i] = self:mul(ret[i], self.ninv)
  end
  return ret
end

TranFFT:initialize()
local a = {}
for i = 1, TranFFT.n do
  a[i] = 0
end

local prime = 200003
local function pmul(x, y) return (x * y) % prime end
local function padd(x, y) return (x + y) % prime end

local p2 = {1}
local p2inv = {0}
for i = 2, prime - 1 do
  p2[i] = (p2[i - 1] * 2) % prime
  p2inv[i] = 0
end
for i = 1, prime - 1 do
  p2inv[p2[i]] = i
end

local n = io.read("*n")
local t = {}
for i = 1, n do
  t[i] = io.read("*n")
  if 0 < t[i] then
    local v = p2inv[t[i]]
    a[v] = a[v] + 1
  end
end
local at = TranFFT:fft(a)
for i = 1, TranFFT.n do
  -- at[i] = TranFFT:mul(at[i], at[i])
  at[i] = TranFFT:twice(at[i])
end
local c = TranFFT:ifft(at)

local ret = {}
for i = 1, prime - 1 do
  ret[i] = 0
end
for i = 1, prime * 2 - 2 do
  local ti = i
  if prime <= ti then
    ti = ti - (prime - 1)
  end
  local v = p2[ti]
  ret[v] = ret[v] + c[i]
end
for i = 1, n do
  if 0 < t[i] then
    local v = pmul(t[i], t[i])
    ret[v] = ret[v] - 1
  end
end
local ans = 0LL
for i = 1, prime - 1 do
  ans = ans + i * mfl(ret[i] / 2)
end
ans = tostring(ans):gsub("LL", "")
print(ans)
-- print(os.clock())

Score : 800 points

Problem Statement

Let’s take a prime P = 200\,003.
You are given N integers A_1, A_2, \ldots, A_N.
Find the sum of ((A_i \cdot A_j) \bmod P) over all N \cdot (N-1) / 2 unordered pairs of elements (i < j).

Please note that the sum isn't computed modulo P.

Constraints

2 \leq N \leq 200\,000

0 \leq A_i < P = 200\,003

All values in input are integers.

Input

Input is given from Standard Input in the following format.

N
A_1 A_2 \cdots A_N

Output

Print one integer — the sum over ((A_i \cdot A_j) \bmod P).

Sample Input 1

4
2019 0 2020 200002

Sample Output 1

474287

The non-zero products are:

2019 \cdot 2020 \bmod P = 78320

2019 \cdot 200002 \bmod P = 197984

2020 \cdot 200002 \bmod P = 197983

So the answer is 0 + 78320 + 197984 + 0 + 0 + 197983 = 474287.

Sample Input 2

5
1 1 2 2 100000

Sample Output 2

600013


x=io.read("*n")
if(x>=30)then
  print("Yes")
else
  print("No")
end

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


function ishot(temp)
  if(temp>=30)then
    return "Yes"
  else
    return "No"
  end
end

io.read(x)
io.write(ishot(x))


k = io.read("*n")
v = 0
for i = 1, k + 1 do
  v = (v * 10 + 7) % k
  if v == 0 then print(i) os.exit() end
end
print(-1)

Score : 300 points

Problem Statement

Takahashi loves the number 7 and multiples of K.

Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)

If the sequence contains no multiples of K, print -1 instead.

Constraints

1 \leq K \leq 10^6

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print an integer representing the position of the first occurrence of a multiple of K. (For example, if the first occurrence is the fourth element of the sequence, print 4.)

Sample Input 1

101

Sample Output 1

4

None of 7, 77, and 777 is a multiple of 101, but 7777 is.

Sample Input 2

2

Sample Output 2

-1

All elements in the sequence are odd numbers; there are no multiples of 2.

Sample Input 3

999983

Sample Output 3

999982


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

local _,red=s:gsub("R","")
for i=1,red do
    if s:sub(i,i)=="R" then
        red=red-1
    end
end
print(red)

Score : 400 points

Problem Statement

An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; R stands for red and W stands for white.

You can do the following two kinds of operations any number of times in any order:

Choose two stones (not necessarily adjacent) and swap them.

Choose one stone and change its color (from red to white and vice versa).

According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

Constraints

2 \leq N \leq 200000

c_i is R or W.

Input

Input is given from Standard Input in the following format:

N
c_{1}c_{2}...c_{N}

Output

Print an integer representing the minimum number of operations needed.

Sample Input 1

4
WWRR

Sample Output 1

2

For example, the two operations below will achieve the objective.

Swap the 1-st and 3-rd stones from the left, resulting in RWWR.

Change the color of the 4-th stone from the left, resulting in RWWW.

Sample Input 2

2
RR

Sample Output 2

0

It can be the case that no operation is needed.

Sample Input 3

8
WRWWRWRR

Sample Output 3

3


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

local n, q = io.read("*n", "*n", "*l")
local t = {}
local s = io.read()
for w in s:gmatch("%d+") do
  table.insert(t, tonumber(w))
end
local ql, qr = {}, {}
local idx = {}
local ret = {}
for iq = 1, q do
  ql[iq], qr[iq] = io.read("*n", "*n")
  idx[iq] = iq
  ret[iq] = 0
end
table.sort(idx, function(a, b) return qr[a] < qr[b] end)
local p = {}
for i = 1, n do
  p[i] = 0
end
local st = SegTree.new(n, function(a, b) return a + b end, 0)
local ti = 1
for iq = 1, q do
  local l, r = ql[idx[iq]], qr[idx[iq]]
  while ti <= r do
    local v = t[ti]
    local old = p[v]
    if 0 < old then
      st:addValue(old, -1)
    end
    p[v] = ti
    st:addValue(ti, 1)
    ti = ti + 1
  end
  ret[idx[iq]] = st:getRange(l, r)
end
print(table.concat(ret, "\n"))

Score : 600 points

Problem Statement

We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.

You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

Constraints

1\leq N,Q \leq 5 \times 10^5

1\leq c_i \leq N

1\leq l_i \leq r_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the response to the i-th query.

Sample Input 1

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

Sample Output 1

2
3
1

The 1-st, 2-nd, and 3-rd balls from the left have the colors 1, 2, and 1 - two different colors.

The 2-st, 3-rd, and 4-th balls from the left have the colors 2, 1, and 3 - three different colors.

The 3-rd ball from the left has the color 1 - just one color.

Sample Input 2

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

Sample Output 2

1
2
2
1
2
2
6
3
3
3


local A, B, C, K = io.read("*n", "*n", "*n" , "*n")

for i = 1, K do
	if C <= B then
		C = C * 2
	elseif B <= A then
		B = B * 2
	else
		break
	end
end

local out = "Yes"
if C <= B or B <= A then
	out = "No"
end

print(out)

Score: 200 points

Problem Statement

M-kun has the following three cards:

A red card with the integer A.

A green card with the integer B.

A blue card with the integer C.

He is a genius magician who can do the following operation at most K times:

Choose one of the three cards and multiply the written integer by 2.

His magic is successful if both of the following conditions are satisfied after the operations:

The integer on the green card is strictly greater than the integer on the red card.

The integer on the blue card is strictly greater than the integer on the green card.

Determine whether the magic can be successful.

Constraints

1 \leq A, B, C \leq 7

1 \leq K \leq 7

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C
K

Output

If the magic can be successful, print Yes; otherwise, print No.

Sample Input 1

7 2 5
3

Sample Output 1

Yes

The magic will be successful if, for example, he does the following operations:

First, choose the blue card. The integers on the red, green, and blue cards are now 7, 2, and 10, respectively.

Second, choose the green card. The integers on the red, green, and blue cards are now 7, 4, and 10, respectively.

Third, choose the green card. The integers on the red, green, and blue cards are now 7, 8, and 10, respectively.

Sample Input 2

7 4 2
3

Sample Output 2

No

He has no way to succeed in the magic with at most three operations.


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

local possession = 1000
local stock = 0

for i = 1, N do
	if A[i - 1] and A[i - 1] < A[i] then
		possession = possession + stock * A[i]
		stock = 0
	end
	if A[i + 1] and A[i + 1] > A[i] then
		stock = floor(possession / A[i])
		possession = possession % A[i]
	end
end

print(tostring(possession):sub(1, -3))

Score: 400 points

Problem Statement

To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives.

He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the next N days will be as follows:

A_1 yen on the 1-st day, A_2 yen on the 2-nd day, ..., A_N yen on the N-th day.

In the i-th day, M-kun can make the following trade any number of times (possibly zero), within the amount of money and stocks that he has at the time.

Buy stock: Pay A_i yen and receive one stock.

Sell stock: Sell one stock for A_i yen.

What is the maximum possible amount of money that M-kun can have in the end by trading optimally?

Constraints

2 \leq N \leq 80

100 \leq A_i \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the maximum possible amount of money that M-kun can have in the end, as an integer.

Sample Input 1

7
100 130 130 130 115 115 150

Sample Output 1

1685

In this sample input, M-kun has seven days of trading. One way to have 1685 yen in the end is as follows:

Initially, he has 1000 yen and no stocks.

Day 1: Buy 10 stocks for 1000 yen. Now he has 0 yen.

Day 2: Sell 7 stocks for 910 yen. Now he has 910 yen.

Day 3: Sell 3 stocks for 390 yen. Now he has 1300 yen.

Day 4: Do nothing.

Day 5: Buy 1 stock for 115 yen. Now he has 1185 yen.

Day 6: Buy 10 stocks for 1150 yen. Now he has 35 yen.

Day 7: Sell 11 stocks for 1650 yen. Now he has 1685 yen.

There is no way to have 1686 yen or more in the end, so the answer is 1685.

Sample Input 2

6
200 180 160 140 120 100

Sample Output 2

1000

In this sample input, it is optimal to do nothing throughout the six days, after which we will have 1000 yen.

Sample Input 3

2
157 193

Sample Output 3

1216

In this sample input, it is optimal to buy 6 stocks in Day 1 and sell them in Day 2, after which we will have 1216 yen.


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

local possession = 1000
local stock = 0

for i = 1, N do
	if A[i - 1] and A[i - 1] < A[i] then
		possession = possession + stock * A[i]
	end
	if A[i + 1] and A[i + 1] > A[i] then
		stock = floor(possession / A[i])
		possession = possession % A[i]
	end
end

print(possession)


local mmi, mma = math.min, math.max
local mab = math.abs
local mfl, mce = math.floor, math.ceil
local bls, brs = bit.lshift, bit.rshift
local n = io.read("*n")
local x, y, p = {}, {}, {}
local flag = {}
for i = 1, n do
  x[i], y[i], p[i] = io.read("*n", "*n", "*n")
  flag[i] = false
end

local function findright(idxes, ofst)
  for i = ofst, #idxes do
    if flag[idxes[i]] then
      return i
    end
  end
  return false
end

local function getmincost(t, linecnt)
  local pos, val, idx = {}, {}, {}
  for k, v in pairs(t) do
    table.insert(pos, k)
    table.insert(val, v)
  end
  if #pos <= linecnt then
    return 0
  end
  for i = 1, #pos do idx[i] = i end
  table.sort(idx, function(a, b) return val[a] > val[b] end)
  for i = 1, linecnt do
    flag[idx[i]] = true
  end
  for i = linecnt + 1, #pos do
    flag[idx[i]] = false
  end
  local retval = 0
  table.sort(idx, function(a, b) return pos[a] < pos[b] end)
  local leftpos = false
  local rightpos = findright(idx, 1)
  for i = 1, #idx do
    local idx_i = idx[i]
    if flag[idx_i] then
      leftpos = rightpos
      if rightpos then
        rightpos = findright(idx, rightpos + 1)
      end
    else
      local cand = mab(pos[idx_i])
      if leftpos then
        cand = mmi(cand, mab(pos[idx_i] - pos[idx[leftpos]]))
      end
      if rightpos then
        cand = mmi(cand, mab(pos[idx_i] - pos[idx[rightpos]]))
      end
      retval = retval + cand * val[idx_i]
    end
  end
  return retval
end

for ik = 0, n do
  local tot = bls(1, n)
  local box = {}
  local ret = 0
  for i = 0, tot - 1 do
    local xs, ys = {}, {}
    local ti = i
    for j = 1, n do
      box[j] = ti % 2 == 0
      if ti % 2 == 0 then
        if not xs[x[j]] then
          xs[x[j]] = p[j]
        else
          xs[x[j]] = xs[x[j]] + p[j]
        end
      else
        if not ys[y[j]] then
          ys[y[j]] = p[j]
        else
          ys[y[j]] = ys[y[j]] + p[j]
        end
      end
      ti = brs(ti, 1)
    end
    local cand = 0
    for xline = 0, ik do
      local yline = ik - xline
      local xcost = getmincost(xs, xline)
      local ycost = getmincost(ys, yline)
      local z = xcost + ycost
      if xline == 0 then
        cand = z
      elseif z < cand then
        cand = z
      end
    end
    if i == 0 then
      ret = cand
    elseif cand < ret then
      ret = cand
    end
  end
  print(ret)
end

Score: 500 points

Problem Statement

New AtCoder City has an infinite grid of streets, as follows:

At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.

A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.

A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.

There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.

M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.

M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.

For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?

Constraints

1 \leq N \leq 15

-10 \ 000 \leq X_i \leq 10 \ 000

-10 \ 000 \leq Y_i \leq 10 \ 000

1 \leq P_i \leq 1 \ 000 \ 000

The locations of the N residential areas, (X_i, Y_i), are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N

Output

Print the answer in N+1 lines.

The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.

Sample Input 1

3
1 2 300
3 3 600
1 4 800

Sample Output 1

2900
900
0
0

When K = 0, the residents of Area 1, 2, and 3 have to walk the distances of 1, 3, and 1, respectively, to reach a railroad.

Thus, the sum of the walking distances of all citizens, S, is 1 \times 300 + 3 \times 600 + 1 \times 800 = 2900.

When K = 1, if we build a railroad along the street corresponding to the line y = 4 in the coordinate plane, the walking distances of the citizens of Area 1, 2, and 3 become 1, 1, and 0, respectively.

Then, S = 1 \times 300 + 1 \times 600 + 0 \times 800 = 900.

We have many other options for where we build the railroad, but none of them makes S less than 900.

When K = 2, if we build a railroad along the street corresponding to the lines x = 1 and x = 3 in the coordinate plane, all citizens can reach a railroad with the walking distance of 0, so S = 0. We can also have S = 0 when K = 3.

The figure below shows the optimal way to build railroads for the cases K = 0, 1, 2.

The street painted blue represents the roads along which we build railroads.

Sample Input 2

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Sample Output 2

13800
1600
0
0
0
0

The figure below shows the optimal way to build railroads for the cases K = 1, 2.

Sample Input 3

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Sample Output 3

26700
13900
3200
1200
0
0
0

The figure below shows the optimal way to build railroads for the case K = 3.

Sample Input 4

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Sample Output 4

2576709
1569381
868031
605676
366338
141903
0
0
0

The figure below shows the optimal way to build railroads for the case K = 4.


local mmi, mma = math.min, math.max
local mab = math.abs
local mfl, mce = math.floor, math.ceil
local bls, brs = bit.lshift, bit.rshift
local n = io.read("*n")
local x, y, p = {}, {}, {}
local flag = {}
for i = 1, n do
  x[i], y[i], p[i] = io.read("*n", "*n", "*n")
  flag[i] = false
end

local function findright(idxes, ofst)
  for i = ofst, #idxes do
    if flag[idxes[i]] then
      return i
    end
  end
  return false
end

local function getmincost(t, idxes, linecnt, debug)
  if debug then print("---") end
  if #idxes <= linecnt then
    return 0
  end
  table.sort(idxes, function(a, b) return p[a] > p[b] end)
  local vv = {}
  local use = 0
  for i = 1, n do flag[i] = false end
  if 0 < linecnt then
    for i = 1, #idxes do
      local idxes_i = idxes[i]
      if not vv[t[idxes_i]] then
        use = use + 1
        flag[idxes_i] = true
        vv[t[idxes_i]] = true
      end
      if use == linecnt then break end
    end
  end
  -- for i = 1, linecnt do
  --   flag[idxes[i]] = true
  -- end
  -- for i = linecnt + 1, #idxes do
  --   flag[idxes[i]] = false
  -- end
  local retval = 0
  table.sort(idxes, function(a, b) return t[a] < t[b] end)
  local leftpos = false
  local rightpos = findright(idxes, 1)
  for i = 1, #idxes do
    local idxes_i = idxes[i]
    if flag[idxes_i] then
      leftpos = rightpos
      if rightpos then
        rightpos = findright(idxes, rightpos + 1)
      end
    else
      local cand = mab(t[idxes_i])
      if leftpos then
        cand = mmi(cand, mab(t[idxes_i] - t[idxes[leftpos]]))
      end
      if rightpos then
        cand = mmi(cand, mab(t[idxes_i] - t[idxes[rightpos]]))
      end
      if debug then print(i, cand, leftpos, rightpos, idxes_i, p[idxes_i]) end
      retval = retval + cand * p[idxes_i]
    end
  end
  if debug then print("sub" .. retval) end
  return retval
end

for ik = 0, n do
  local tot = bls(1, n)
  local box = {}
  local ret = 0
  for i = 0, tot - 1 do
    local xs, ys = {}, {}
    local ti = i
    for j = 1, n do
      box[j] = ti % 2 == 0
      if ti % 2 == 0 then
        table.insert(xs, j)
      else
        table.insert(ys, j)
      end
      ti = brs(ti, 1)
    end
    local cand = 0
    for xline = 0, ik do
      local yline = ik - xline
      local xcost = getmincost(x, xs, xline)
      local ycost = getmincost(y, ys, yline)
      local z = xcost + ycost
      do
        if ik == 4 and xline == 2 and table.concat(xs) == "6842" then
          -- getmincost(y, ys, yline, true)
          -- print(table.concat(xs) .. " " .. table.concat(ys), xcost, ycost)
        end
      end
      if xline == 0 then
        cand = z
      elseif z < cand then
        cand = z
      end
    end
    if i == 0 then
      ret = cand
    elseif cand < ret then
      ret = cand
    end
  end
  print(ret)
end


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)
        sort(t, function (i1, i2)
            return inv[i1] < inv[i2]
        end)
        local state = 0
        local recentfwinv = -200000
        for _,i in ipairs(t) do
            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

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


n = io.read("*n")
c = 0
for i = 1, n do
  a = io.read("*n")
  if (i * a) % 2 == 1 then c = c + 1 end
end
print(c)

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


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 N = read.nl()
local f = {'AC', 'WA', 'TLE', 'RE'}
local t = {}
for i=1,N do
    local s = read.l():gsub('%s', '')
    t[s] = (t[s] or 0) + 1
end
for i=1,4 do
    print(f[i] .. ' x ' .. (t[f[i]] or 0))
end

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 s = io.read()
local num = tonumber(s)
local outstr = ""

local map = {
	["AC"] = 0,
	["WA"] = 0,
	["TLE"] = 0,
	["RE"] = 0,
}

for i=1,num do
	s = io.read()
	if map[s] then
		map[s] = map[s] + 1
	end
	for k,v in pairs(map) do
		outstr = outstr .. k .. " x " .. v .. "\n"
	end
end

print(outstr)


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 H, W, K = read.nnnl()
local C = {}
for i=1,H do
    C[i] = read.l():totable()
end

local function getb(mh, mw)
    local b = 0
    for h=1,H do
        if mh & (1<<(h-1)) ~= 0 then
            for w=1,W do
                if mw & (1<<(w-1)) ~= 0 then
                    if C[h][w] == '#' then
                        b = b + 1
                    end
                end
            end
        end
    end
    return b
end

local c = 0
for mh=0,math.floor(2^H)-1 do
    for mw=0,math.floor(2^W)-1 do
        if getb(mh,mw) == K then
            c = c + 1
        end
    end
end
print(c)

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 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 function clone(t)
    local c = {}
    for k,v in pairs(t) do
        c[k] = v
    end
    return c
end
--
local H, W, K = read.nnnl()
local C = {}
for i=1,H do
    C[i] = read.l():totable()
end

local function getb(mh, mw)
    local b = 0
    for h=1,H do
        if not mh[h] then
            for w=1,W do
                if not mw[w] then
                    if C[h][w] == '#' then
                        b = b + 1
                    end
                end
            end
        end
    end
    return b
end

local count = 0
local function dfs(h, w, mh, mw)
    if h < H then
        h = h + 1
        dfs(h, w, mh, mw)
        local mh1 = clone(mh)
        mh1[h] = 1
        dfs(h, w, mh1, mw)
    elseif w < W then
        w = w + 1
        dfs(h, w, mh, mw)
        local mw1 = clone(mw)
        mw1[w] = 1
        dfs(h, w, mh, mw1)
    else
        local b = getb(mh, mw)
        if b == K then
            count = count + 1
        end
    end
end

dfs(0, 0, {}, {})
print(count)


local a = io.read()
local b = io.read()
local c = io.read()

local num = 0
for i=1,tonumber(a)*tonumber(b) do
	s = io.read()
	if s == "#" then
		num = num + 1
	end
end
if num < tonumber(c) then
	print(0)
end
local n = 0
for i= c,num-1 do
	n = n+ i
end
print(n)


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

function ru()
   return unpack(rl())
end

function pu(x, ...)
   if x then
      io.write(x, ' ')
      return pu(...)
   else
      io.write('\n')
   end
end

N = ru()
A = rl()

table.sort(A)

r = -A[N]
t = 0
for i = N, 1, -1 do
   r = r + A[i]
   t = t + 1
   if t >= N then break end
   r = r + A[i]
   t = t + 1
   if t >= N then break end
end

pu(r)

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 D=io.read"*n"
local c={}
for i=1,26 do c[i]=io.read"*n"end
local s={}
for i=1,D do s[i]={}for j=1,26 do s[i][j]=io.read"*n"end end
local t={}
for i=1,D do t[i]=io.read"*n"end

local last={}
for i=1,26 do
last[i]=0
end

local a=0
for i=1,D do
	last[t[i]]=i
	for j=1,26 do
		a=a-c[j]*(i-last[j])
	end
	a=a+s[i][t[i]]
	print(a)
end

(Please read problem A first. The maximum score you can get by solving this problem B is 1, which will have almost no effect on your ranking.)

Beginner's Guide

Let's first write a program to calculate the score from a pair of input and output. You can know the total score by submitting your solution, or an official program to calculate a score is often provided for local evaluation as in this contest. Nevertheless, writing a score calculator by yourself is still useful to check your understanding of the problem specification. Moreover, the source code of the score calculator can often be reused for solving the problem or debugging your solution. So it is worthwhile to write a score calculator unless it is very complicated.

Problem Statement

You will be given a contest schedule for D days.
For each d=1,2,\ldots,D, calculate the satisfaction at the end of day d.

Input

Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A.

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}
t_1
t_2
\vdots
t_D

The constraints and generation methods for the input part are the same as those for Problem A.

For each d, t_d is an integer satisfying 1\leq t_d \leq 26, and your program is expected to work correctly for any value that meets the constraints.

Output

Let v_d be the satisfaction at the end of day d.
Print D integers v_d to Standard Output in the following format:

v_1
v_2
\vdots
v_D

Sample Input 1

5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192
1
17
13
14
13

Sample Output 1

18398
35037
51140
65837
79325

Note that this example is a small one for checking the problem specification. It does not satisfy the constraint D=365 and is never actually given as a test case.

Next Step

We can build a solution (schedule) for this problem in the order of day 1, day 2, and so on. And for every partial solution we have built, we can calculate the goodness (satisfaction) by using the above score calculator. So we can construct the following algorithm: for each d=1,2,\ldots,D, we select the contest type that maximizes the satisfaction at the end of day d. You may have already encountered this kind of "greedy algorithms" in algorithm contests such as ABC. Greedy algorithms can guarantee the optimality for several problems, but unfortunately, it doesn't ensure optimality for this problem. However, even if it does not ensure optimality, we can still obtain a reasonable solution in many cases. Let's go back to Problem A and implement the greedy algorithm by utilizing the score calculator you just implemented!

Greedy methods can be applied to a variety of problems, are easy to implement, and often run relatively fast compared to other methods. Greedy is often the most powerful method when we need to process huge inputs.
We can further improve the score by changing the greedy selection criteria (evaluation function), keeping multiple candidates instead of focusing on one best partial solution (beam search), or using the output of greedy algorithms as an initial solution of other methods.
For more information, please refer to the editorial that will be published after the contest.


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

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 a = io.read("*n", "*l")
print(a+a*a+a*a*a)
-- print(a+a*a+a*a*a)
-- print(a+a*a+a*a*a)
-- print(a+a*a+a*a*a)


local s=io.read()
local t=io.read()

local counter=0
for i=1,#s do
    if s:sub(i,i)~=t:sub(i,i) then
        counter=counter+1
    end
end
print(counter)

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 = {}, {}
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
--]]
---[[ パターン3

for i = 1, S:len() do
	if S:byte(i) ~= T:byte(i) then
		count = count + 1
	end
end
--]]

print(count)


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 = {}, {}
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)


local mfl, mce = math.floor, math.ceil
local n = io.read("*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
local xor = 0
for i = 3, n do
  xor = xor ~ a[i]
end
local sum = a[1] + a[2]
if sum < xor then
  print(-1)
  os.exit()
end
local b_xor, b_sum = {}, {}
while 0 < sum do
  table.insert(b_sum, sum % 2)
  table.insert(b_xor, xor % 2)
  sum = mfl(sum / 2)
  xor = mfl(xor / 2)
end
local dig = #b_sum
local moveup = false
local state = {}
for i = 1, dig do state[i] = 0 end
-- state of bit of a[1] and a[2]
-- 1: [0, 0], 2: [1, 1], 3: [0, 1] or [1, 0]
for idig = dig, 1, -1 do
  if b_sum[idig] == 1 then
    if b_xor[idig] == 1 then
      if moveup then
        print(-1)
        os.exit()
      else
        state[idig] = 3
      end
    else
      if moveup then
        state[idig] = 2
      else
        state[idig] = 1
      end
      moveup = true
    end
  else-- sum = 0
    if b_xor[idig] == 1 then
      if moveup then
        state[idig] = 3
      else
        print(-1)
        os.exit()
      end
    else
      if moveup then
        state[idig] = 2
      else
        state[idig] = 1
      end
      moveup = false
    end
  end
end
local alim = {}
do
  local tmp = a[1]
  for i = 1, dig do
    alim[i] = tmp % 2
    tmp = mfl(tmp / 2)
  end
end
local tbl = {}
for i = 1, dig do tbl[i] = 0 end

local function dfs(idig, limit)
  if idig == 0 then return true end
  if limit then
    if alim[idig] == 0 then
      if state[idig] == 2 then
        return false
      else
        tbl[idig] = 0
        return dfs(idig - 1, true)
      end
    else
      if state[idig] == 2 then
        tbl[idig] = 1
        return dfs(idig - 1, true)
      elseif state[idig] == 1 then
        tbl[idig] = 0
        return dfs(idig - 1, false)
      else
        tbl[idig] = 1
        local ret = dfs(idig - 1, true)
        if ret then return true
        else
          tbl[idig] = 0
          return dfs(idig - 1, false)
        end
      end
    end
  else
    if state[idig] == 1 then
      tbl[idig] = 0
      return dfs(idig - 1, false)
    else
      tbl[idig] = 1
      return dfs(idig - 1, false)
    end
  end
end

local ret = dfs(dig, true)
if not ret then
  print(-1)
  os.exit()
end
local ans = 0
local mul = 1
for i = 1, dig do
  ans = ans + mul * tbl[i]
  mul = mul * 2
end
if ans == 0 then
  print(-1)
else
  print(a[1] - ans)
end

Score : 600 points

Problem Statement

There are N piles of stones. The i-th pile has A_i stones.

Aoki and Takahashi are about to use them to play the following game:

Starting with Aoki, the two players alternately do the following operation:

Operation: Choose one pile of stones, and remove one or more stones from it.

When a player is unable to do the operation, he loses, and the other player wins.

When the two players play optimally, there are two possibilities in this game: the player who moves first always wins, or the player who moves second always wins, only depending on the initial number of stones in each pile.

In such a situation, Takahashi, the second player to act, is trying to guarantee his win by moving at least zero and at most (A_1 - 1) stones from the 1-st pile to the 2-nd pile before the game begins.

If this is possible, print the minimum number of stones to move to guarantee his victory; otherwise, print -1 instead.

Constraints

2 \leq N \leq 300

1 \leq A_i \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum number of stones to move to guarantee Takahashi's win; otherwise, print -1 instead.

Sample Input 1

2
5 3

Sample Output 1

1

Without moving stones, if Aoki first removes 2 stones from the 1-st pile, Takahashi cannot win in any way.

If Takahashi moves 1 stone from the 1-st pile to the 2-nd before the game begins so that both piles have 4 stones, Takahashi can always win by properly choosing his actions.

Sample Input 2

2
3 5

Sample Output 2

-1

It is not allowed to move stones from the 2-nd pile to the 1-st.

Sample Input 3

3
1 1 2

Sample Output 3

-1

It is not allowed to move all stones from the 1-st pile.

Sample Input 4

8
10 9 8 7 6 5 4 3

Sample Output 4

3

Sample Input 5

3
4294967297 8589934593 12884901890

Sample Output 5

1

Watch out for overflows.


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

Score : 100 points

Problem Statement

An uppercase or lowercase English letter \alpha will be given as input.
If \alpha is uppercase, print A; if it is lowercase, print a.

Constraints

\alpha is an uppercase (A - Z) or lowercase (a - z) English letter.

Input

Input is given from Standard Input in the following format:

α

Output

If \alpha is uppercase, print A; if it is lowercase, print a.

Sample Input 1

B

Sample Output 1

A

B is uppercase, so we should print A.

Sample Input 2

a

Sample Output 2

a

a is lowercase, so we should print a.


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 N = 26
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 and n ~= 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)

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 n=io.read("n")
local t={}
while n>0 do
    local mod=n%26
    if mod==0 then
        mod=26
    end
    table.insert(t,mod+96)
    n=n-mod
    n=n//26
end

local answer={}
for i=#t,1,-1 do
    table.insert(answer,string.char(t[i]))
end
print(table.concat(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 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 N = read.n()
local a = 0x61
local z = 0x7a
local k = z - a + 1
local t = {}
local n = N
while n > 0 do
    local x = n % k
    --print(a, x)
    table.insert(t, string.char(a + x - 1))
    n = n // k
end
local sr = table.concat(t, "")
local ans = sr:reverse()
print(ans)


N=io.read"*n"
i=1
s=0
while true do
	s=s+26^i
	if(N<s)then break end
	i=i+1
end
s=N-s+26^i-1
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 read = io.read
local insert = table.insert

local N = read("*n")
local key_A = {}
for i = 1, N do
	local A = read("*n")
	if key_A[A] then
		key_A[A] = key_A[A] + 1
	else
		key_A[A] = 1
	end
end

local total = 0
for key, value in pairs(key_A) do
	total = total + key * value
end

local out = {}
local Q = read("*n")
for i = 1, Q do
	local B, C = read("*n", "*n")
	if key_A[B] and key_A[C] then
		total = total - B*key_A[B] + C*key_A[B]
		key_A[C] = key_A[C] + key_A[B]
		key_A[B] = nil
	elseif key_A[B] then
		total = total - B*key_A[B] + C*key_A[B]
		key_A[C] = key_A[B]
		key_A[B] = nil
	end
	out[i] = total
end

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

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


N=io.read"*n"
t={}
for i=1,N do
	n=io.read"*n"
	t[n]=(t[n]or 0)+1
end
Q=io.read"*n"

s=0
for k,v in pairs(t)do
	s=s+k*v
end

for i=1,Q do
	B=io.read"*n"
	C=io.read"*n"

	if(t[B])then
		s=s-t[B]*B+t[B]*C
		t[C]=(t[C]or 0)+t[B]
		t[B]=nil
	end

	print(s)

end


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, '*'..string.sub(k, i, i)) end local r = io.read local u = table.unpack or unpack return function() return r(u(a)) end end})
read.N = function(N) local t={} for i=1,N do t[i]=read.n() end return t end
string.totable = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
local function array(dimension, default_val) assert(type(default_val) ~= 'table') local n=dimension local m={}if default_val~=nil then m[1]={__index=function()return default_val end}end for i=2,n do m[i]={__index=function(p, k)local c=setmetatable({},m[i-1])rawset(p,k,c)return c end}end return setmetatable({},m[n])end
local function tostringxx(o, depth) depth = depth or 0 if depth > 10 then return "<too deep!>" end if o == _G then return "<_G>" end local indent0 = (" "):rep((depth) * 2) local indent1 = (" "):rep((depth+1) * 2) local indent2= (" "):rep((depth+2) * 2) if type(o) == 'table' then local keys = {} local types = {} for k in pairs(o) do types[type(k)] = true table.insert(keys, k) end local types_count = 0 local lasttype for k in pairs(types) do types_count = types_count + 1 lasttype = k end if types_count == 1 and (lasttype == 'string' or lasttype == 'number') then table.sort(keys) end local inside = {} for i=1,#keys do local k = keys[i] local v = o[k] if type(k) == 'string' then k = string.format('%q', k) end table.insert(inside, indent1 .. '['..tostring(k)..'] = ' .. tostringxx(v, depth + 1)) end return '{\n' .. table.concat(inside, ',\n') .. '\n' .. indent0 .. '}' else if type(o) == 'string' then o = string.format('%q', o) end return tostring(o) end end
local function richtraceback() local x = 2 while true do local info = debug.getinfo(x) if not info then break end local fname = '<' .. info.short_src .. ":" .. info.linedefined .. ">" if info.name then fname = info.name end print(info.short_src .. ":" .. info.currentline .. ": in " .. ("%q"):format(fname)) print(" LOCALS:") local p = 1 while true do local name, val = debug.getlocal(x,p) if not name then break end print(" " .. name .. ": " .. tostringxx(val, 3)) p = p + 1 end print(" UPVALUES:") for p=1,info.nups do local name, val = debug.getupvalue(info.func,p) if not name then break end print(" " .. name .. ": " .. tostringxx(val, 3)) end x = x + 1 end end
local function myassert(b) if not b then richtraceback() error("assertion failed") end end
-----------------------
local N = read.n()
local sum = 0
local nums = {}
for i=1,N do
    local a = read.n()
    sum = sum + a
    nums[a] = (nums[a] or 0) + 1
end
local Q = read.n()
for i=1,Q do
    local b, c = read.nn()
    local cnt = (nums[b] or 0)
    local diff = cnt * c - cnt * b
    sum = sum + diff
    nums[b] = 0
    nums[c] =  (nums[c] or 0) + cnt
    print(sum)
end


-- 解法見た
local read = io.read
local xor = bit.bxor

local N = read("*n")
local S = 0
local a = {}
for i = 1, N do
	a[i] = read("*n")
end

S = xor(unpack(a))

local out = {}
for i = 1, N do
	out[i] = xor(S, a[i])
end

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

Score : 500 points

Problem Statement

There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.

Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.

Recently, they learned the operation called xor (exclusive OR).

What is xor?

For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is defined as follows:

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

For example, 3~\textrm{xor}~5 = 6.

They wanted to use this operation quickly, so each of them calculated the xor of the integers written on their scarfs except his scarf.

We know that the xor calculated by Snuke Cat i, that is, the xor of the integers written on the scarfs except the scarf of Snuke Cat i is a_i.
Using this information, restore the integer written on the scarf of each Snuke Cat.

Constraints

All values in input are integers.

2 \leq N \leq 200000

N is even.

0 \leq a_i \leq 10^9

There exists a combination of integers on the scarfs that is consistent with the given information.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print a line containing N integers separated with space.

The i-th of the integers from the left should represent the integer written on the scarf of Snuke Cat i.

If there are multiple possible solutions, you may print any of them.

Sample Input 1

4
20 11 9 24

Sample Output 1

26 5 7 22

5~\textrm{xor}~7~\textrm{xor}~22 = 20

26~\textrm{xor}~7~\textrm{xor}~22 = 11

26~\textrm{xor}~5~\textrm{xor}~22 = 9

26~\textrm{xor}~5~\textrm{xor}~7 = 24

Thus, this output is consistent with the given information.


local mod = 1000000007
local mfl = math.floor

local function bmul(x, y)
  return (x * y) % mod
end

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

local fact = {1}
local invs = {1}
local invfact = {1}
for i = 2, 2000000 do
  fact[i] = bmul(fact[i - 1], i)
  invs[i] = bmul(mfl(mod / i), mod - invs[mod % i])
  invfact[i] = bmul(invfact[i - 1], invs[i])
end

local function getCombQ(n, k)
  if k == 0 or k == n then return 1 end
  return bmul(fact[n], bmul(invfact[k], invfact[n - k]))
end

local pow25 = {1}
local pow26 = {1}
for i = 2, 1000010 do
  pow25[i] = bmul(pow25[i - 1], 25)
  pow26[i] = bmul(pow26[i - 1], 26)
end

local k = io.read("*n", "*l")
local s = io.read()
local n = #s
local ret = 0
for j = 0, k do
  local z = getCombQ(n + j - 1, n - 1)
  z = bmul(z, pow25[j + 1])
  local rem = k - j
  z = bmul(z, pow26[rem + 1])
  ret = badd(ret, z)
end
print(ret)

Score: 600 points

Problem Statement

How many strings can be obtained by applying the following operation on a string S exactly K times: "choose one lowercase English letter and insert it somewhere"?

The answer can be enormous, so print it modulo (10^9+7).

Constraints

K is an integer between 1 and 10^6 (inclusive).

S is a string of length between 1 and 10^6 (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

K
S

Output

Print the number of strings satisfying the condition, modulo (10^9+7).

Sample Input 1

5
oof

Sample Output 1

575111451

For example, we can obtain proofend, moonwolf, and onionpuf, while we cannot obtain oofsix, oofelevennn, voxafolt, or fooooooo.

Sample Input 2

37564
whydidyoudesertme

Sample Output 2

318008117


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 fact = {1}
local invs = {1}
local invfact = {1}
for i = 2, 2000000 do
  fact[i] = bmul(fact[i - 1], i)
  invs[i] = bmul(mfl(mod / i), mod - invs[mod % i])
  invfact[i] = bmul(invfact[i - 1], invs[i])
end

local function getComb(n, k)
  if k == 0 or k == n then return 1 end
  return bmul(fact[n], bmul(invfact[k], invfact[n - k]))
end

local pow25 = {1}
local pow26 = {1}
for i = 2, 2000010 do
  pow25[i] = bmul(pow25[i - 1], 25)
  pow26[i] = bmul(pow26[i - 1], 26)
end

local k = io.read("*n", "*l")
local s = io.read()
local n = #s
local ret = 0
for j = 0, k do
  local z = getComb(n + j - 1, n - 1)
  z = bmul(z, pow25[j + 1])
  local rem = k - j
  z = bmul(z, pow26[rem + 1])
  ret = badd(ret, z)
end
print(ret)


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

Score : 100 points

Problem Statement

We have five variables x_1, x_2, x_3, x_4, and x_5.

The variable x_i was initially assigned a value of i.

Snuke chose one of these variables and assigned it 0.

You are given the values of the five variables after this assignment.

Find out which variable Snuke assigned 0.

Constraints

The values of x_1, x_2, x_3, x_4, and x_5 given as input are a possible outcome of the assignment by Snuke.

Input

Input is given from Standard Input in the following format:

x_1 x_2 x_3 x_4 x_5

Output

If the variable Snuke assigned 0 was x_i, print the integer i.

Sample Input 1

0 2 3 4 5

Sample Output 1

1

In this case, Snuke assigned 0 to x_1, so we should print 1.

Sample Input 2

1 2 0 4 5

Sample Output 2

3


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

local a
for i=1,5 do
if(io.read"*n"==0)then a=i break end
end
print(a)


X=io.read"*n"
Y=io.read"*n"
if(Y%2==1)then print"No"end
print(X*2<=Y and Y<=X*4 and "Yes" or "No")

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

local h, w, k = io.read("*n", "*n", "*n")
local inf = h * w * k + 1
local x1, y1 = io.read("*n", "*n")
local sidx = (x1 - 1) * w + y1
local x2, y2 = io.read("*n", "*n", "*l")
local tidx = (x2 - 1) * w + y2
local len = {}
local asked = {}
for i = 1, h do
  local s = io.read()
  for j = 1, w do
    local idx = (i - 1) * w + j
    local f = s:sub(j, j) ~= "."
    for k = -3, 0 do
      len[idx * 4 + k] = inf
      asked[idx * 4 + k] = f
    end
  end
end
len[sidx * 4 - 3] = 0
len[sidx * 4 - 2] = 0
len[sidx * 4 - 1] = 0
len[sidx * 4] = 0

local n = h * w * 4
asked[n + 1] = true

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

local st = SegTree.new(n, mergefunc, n + 1)

local function walk(src, dst, cost)
  if not asked[dst] and len[src] + cost < len[dst] then
    len[dst] = len[src] + cost
    st:update(dst)
  end
end

for i = 1, n do
  local src = st.stage[1]
  if asked[src] then break end
  asked[src] = true
  st:update(src)
  local idx = mce(src / 4)

  local l = len[src]
  local z = mce(l / k) * k - l
  if src % 4 == 1 then
    -- to left
    if 1 < w and idx % w ~= 1 then
      walk(src, src - 4, 1)
    end
    walk(src, src + 1, z)
    walk(src, src + 2, z)
    walk(src, src + 3, z)
  elseif src % 4 == 2 then
    -- to right
    if 1 < w and idx % w ~= 0 then
      walk(src, src + 4, 1)
    end
    walk(src, src - 1, z)
    walk(src, src + 1, z)
    walk(src, src + 2, z)
  elseif src % 4 == 3 then
    -- to up
    if w < idx then
      walk(src, src - 4 * w, 1)
    end
    walk(src, src - 2, z)
    walk(src, src - 1, z)
    walk(src, src + 1, z)
  else
    -- to down
    if idx <= (h - 1) * w then
      walk(src, src + 4 * w, 1)
    end
    walk(src, src - 3, z)
    walk(src, src - 2, z)
    walk(src, src - 1, z)
  end
end

local ret = mmi(len[tidx * 4 - 3], len[tidx * 4 - 2], len[tidx * 4 - 1], len[tidx * 4])
if inf <= ret then
  print(-1)
else
  local l = mce(ret / k)
  print(l)
end

Score : 600 points

Problem Statement

Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.

Some of the squares have a lotus leaf on it and cannot be entered.
The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is ..

In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.

Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2).
If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact.

Constraints

1 \leq H,W,K \leq 10^6

H \times W \leq 10^6

1 \leq x_1,x_2 \leq H

1 \leq y_1,y_2 \leq W

x_1 \neq x_2 or y_1 \neq y_2.

c_{i,j} is . or @.

c_{x_1,y_1} = .

c_{x_2,y_2} = .

All numbers in input are integers.

Input

Input is given from Standard Input in the following format:

H W K
x_1 y_1 x_2 y_2
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 the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible.

Sample Input 1

3 5 2
3 2 3 4
.....
.@..@
..@..

Sample Output 1

5

Initially, Snuke is at the square (3,2).
He can reach the square (3, 4) by making five strokes as follows:

From (3, 2), go west one square to (3, 1).

From (3, 1), go north two squares to (1, 1).

From (1, 1), go east two squares to (1, 3).

From (1, 3), go east one square to (1, 4).

From (1, 4), go south two squares to (3, 4).

Sample Input 2

1 6 4
1 1 1 6
......

Sample Output 2

2

Sample Input 3

3 3 1
2 1 2 3
.@.
.@.
.@.

Sample Output 3

-1


Score : 100 points

Problem Statement

When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters.
You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.

Constraints

3 \leq |S| \leq 20

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print your answer.

Sample Input 1

takahashi

Sample Output 1

tak

Sample Input 2

naohiro

Sample Output 2

nao


a, b = io.read("*n", "*n")
c, d = io.read("*n", "*n")
t = io.read("*n")
f = math.abs(a - c) <= t * (b - d)
print(f and "YES" or "NO")

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