local s = io.read()
local n = #s + 1
local llen, rlen = 0, 0
local toup = true
local lpos = s:sub(1, 1) == ">" and 0 or 1
local turnpos = 0
local sum = 0
if s:sub(n - 1, n - 1) == "<" then
  s = s .. ">"
else
  s = s .. "<"
end
for i = 1, n do
  local ss = s:sub(i, i)
  if ss == "<" then
    if not toup then
      local rlen = i - turnpos
      if llen < rlen then
        sum = sum + llen * (llen - 1) // 2 + rlen * (rlen + 1) // 2
      else
        sum = sum + llen * (llen + 1) // 2 + rlen * (rlen - 1) // 2
      end
      -- print(sum)
      lpos = i
      toup = true
    end
  else
    if toup then
      turnpos = i
      llen = i - lpos
      toup = false
    end
  end
end
if not toup then
  local rlen = n - turnpos
  -- print(rlen)
  if llen < rlen then
    sum = sum + llen * (llen - 1) // 2 + rlen * (rlen + 1) // 2
  else
    sum = sum + llen * (llen + 1) // 2 + rlen * (rlen - 1) // 2
  end
end
print(sum)


local mma, mmi = math.max, math.min
local n = io.read("*n")
local t = {}
for i = 1, n do
  t[i] = {io.read("*n", "*n")}
  t[i][3] = i
end
local lmaxp, rminp = 1, 1
for i = 2, n do
  if t[lmaxp][1] < t[i][1] then
    lmaxp = i
  end
  if t[i][2] < t[rminp][2] then
    rminp = i
  end
end
local cand = mma(0, t[rminp][2] - t[lmaxp][1] + 1)
do
  local maxlen = 0
  for i = 1, n do
    if i ~= lmaxp and i ~= rminp then
      maxlen = mma(maxlen, t[i][2] - t[i][1] + 1)
    end
  end
  cand = cand + maxlen
end
if lmaxp ~= rminp then
  local l_r, r_l = t[rminp][2], t[lmaxp][1]

  local l_l, r_r = false, t[lmaxp][2]
  table.sort(t, function(a, b) return a[1] > b[1] end)
  for i = 1, n do
    if t[i][3] ~= lmaxp then
      l_l = t[i][1]
      cand = mma(cand, mma(0, l_r - l_l + 1) + mma(0, r_r - r_l + 1))
    end
    if t[i][3] ~= rminp then
      r_r = mmi(r_r, t[i][2])
    end
  end
  cand = mma(cand, mma(0, l_r - l_l + 1) + mma(0, r_r - r_l + 1))
end
print(cand)

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

Score : 600 points

Problem Statement

10^9 contestants, numbered 1 to 10^9, will compete in a competition.
There will be two contests in this competition.

The organizer prepared N problems, numbered 1 to N, to use in these contests.
When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclusive), and will not be solved by any other contestants.

The organizer will use these N problems in the two contests.
Each problem must be used in exactly one of the contests, and each contest must have at least one problem.

The joyfulness of each contest is the number of contestants who will solve all the problems in the contest.
Find the maximum possible total joyfulness of the two contests.

Constraints

2 \leq N \leq 10^5

1 \leq L_i \leq R_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 R_1
L_2 R_2
\vdots
L_N R_N

Output

Print the maximum possible total joyfulness of the two contests.

Sample Input 1

4
4 7
1 4
5 8
2 5

Sample Output 1

6

The optimal choice is:

Use Problem 1 and 3 in the first contest. Contestant 5, 6, and 7 will solve both of them, so the joyfulness of this contest is 3.

Use Problem 2 and 4 in the second contest. Contestant 2, 3, and 4 will solve both of them, so the joyfulness of this contest is 3.

The total joyfulness of these two contests is 6. We cannot make the total joyfulness greater than 6.

Sample Input 2

4
1 20
2 19
3 18
4 17

Sample Output 2

34

Sample Input 3

10
457835016 996058008
456475528 529149798
455108441 512701454
455817105 523506955
457368248 814532746
455073228 459494089
456651538 774276744
457667152 974637457
457293701 800549465
456580262 636471526

Sample Output 3

540049931

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

local mma, mmi = math.max, math.min
local n = io.read("*n")
local l, r = {}, {}
local s_idx = {}
for i = 1, n do
  l[i], r[i] = io.read("*n", "*n")
  s_idx[i] = i
end
table.sort(s_idx, function(x, y)
  if l[x] == l[y] then
    return r[x] < r[y]
  else
    return l[x] < l[y]
  end
end)
local lmin_idx = s_idx[1]
-- local rmax_idx = s_idx[n] == lmin_idx and s_idx[n - 1] or s_idx[n]
local rmax_idx, tmpscore = 0, 0
for i = 1, n do
  if lmin_idx ~= i then
    if rmax_idx == 0 then
      rmax_idx = i
      tmpscore = mmi(r[i], r[lmin_idx]) - l[i]
    else
      local ts2 = mmi(r[i], r[lmin_idx]) - l[i]
      if ts2 < tmpscore then
        rmax_idx = i
        tmpscore = ts2
      elseif ts2 == tmpscore then
        if r[rmax_idx] < r[i] then
          rmax_idx = i
          tmpscore = ts2
        end
      end
    end
  end
end
local lpoint, rpoint = r[lmin_idx] - l[lmin_idx] + 1, r[rmax_idx] - l[rmax_idx] + 1
local lp, rp = {}, {}
for i = 1, n do
  if i ~= rmax_idx and i ~= lmin_idx then
    table.insert(lp, mma(0, mmi(r[i], r[lmin_idx]) - l[i] + 1))
    table.insert(rp, mma(0, mmi(r[i], r[rmax_idx]) - mma(l[i], l[rmax_idx]) + 1))
  end
end
-- table.insert(lp, lpoint)
-- table.insert(rp, 0)
table.insert(lp, -1)
table.insert(rp, rpoint)
local t_idx = {}
for i = 1, n - 1 do
  t_idx[i] = i
end
table.sort(t_idx, function(x, y)
  if lp[x] == lp[y] then
    return rp[x] < rp[y]
  else
    return lp[x] < lp[y]
  end
end)
local inf = 1000000007
local st = SegTree.new(n - 1, function(x, y) return mmi(x, y) end, inf)
local ans = 0
for i = 1, n - 1 do
  -- print("ADD", i, t_idx[i], rp[t_idx[i]])
  st:setValue(i, rp[t_idx[i]])
  local lv = i == n - 1 and lpoint or lp[t_idx[i + 1]]
  local ret = mma(0, lv) + st.stage[1][1]
  -- print(i, mma(0, lv), st.stage[1][1])
  ans = mma(ans, ret)
end
print(ans)


N=io.read"*n"
print((function()
	for i=1,9 do
		local a=N/i
		if(i==math.floor(i)and 1<=i and i<=9)then return true end
	end
return false end)()and"Yes"or"No")

Score : 200 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.

Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

10 can be represented as, for example, 2 \times 5.

Sample Input 2

50

Sample Output 2

No

50 cannot be represented as the product of two integers between 1 and 9.

Sample Input 3

81

Sample Output 3

Yes


local n = io.read("*n")
local f = false
for i = 1, 9 do
  if n % i == 0 and n // i < 10 then f = true end
end
print(f and "Yes" or "No")


local n = io.read("*n")
local t = {}
for i = 1, 9 do
	for j = 1, 9 do
		t[i * j] = true
	end
end
if t[n] then
	print("Yes")
else
	print("No")
end


local N = io.read("n")
for a=1,9 do
  for b=1,9 do
    if a*b > 100 then
      break
    end
    if a*b == N then
      print("Yes")
      return
    end
  end
end
print("No")


N=io.read"*n"
m=math.huge
for i=1,math.sqrt(N)do
	local a=N/i
	if(a==math.floor(a))then m=math.min(m,i+a)end
end
print(m-2)

Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


    n=io.read("*n")

    p=n
    l=1

    for i=2, 9 do
      if (n/i)<p and n%i==0 then
        p=n/i
        l=i
      end
    end

    if l==1 then
      print(n-1)
    else
      print(p*l-2)
    end


local a, b, x = io.read("*n", "*n", "*n")
local height = x / a / a--高さ
local diff = b - height--口までの高さ
if height >= diff then
	local diag = math.sqrt(a*a + diff*diff*4)
	print(math.deg(math.atan((diff * 2) / a)))
else
	local bottom = a * height * 2 / b
	print(math.deg(math.atan(b / bottom)))
end

Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


local a, b = io.read("*n", "*n")
print(math.max(0, a - b - b))

Score : 100 points

Problem Statement

The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the total horizontal length of the uncovered parts of the window.

Sample Input 1

12 4

Sample Output 1

4

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


n = io.read("*n")
t = {}
for i = 1, n do
  t[i] = io.read("*n")
end
r = 0
for i = 1, n - 1 do for j = i + 1, n do
  r = r + t[i] * t[j]
end end
print(r)

Score : 200 points

Problem Statement

It's now the season of TAKOYAKI FESTIVAL!

This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i.

As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points.

There are \frac{N \times (N - 1)}{2} ways to choose two from the N takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these \frac{N \times (N - 1)}{2} values.

Constraints

All values in input are integers.

2 \leq N \leq 50

0 \leq d_i \leq 100

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the N takoyaki served.

Sample Input 1

3
3 1 2

Sample Output 1

11

There are three possible choices:

Eat the first and second takoyaki. You will restore 3 health points.

Eat the second and third takoyaki. You will restore 2 health points.

Eat the first and third takoyaki. You will restore 6 health points.

The sum of these values is 11.

Sample Input 2

7
5 0 7 8 3 3 2

Sample Output 2

312


local n = io.read("*n")
local ans = 1
local str = io.read("*l")
for i = 1, #str-1 do
  if string.sub(str, i, i) ~= string.sub(str, i+1, i+1) then
    ans = ans + 1
  end
end
print(ans)

Score : 300 points

Problem Statement

There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.

Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.

Ultimately, how many slimes will be there?

Constraints

1 \leq N \leq 10^5

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the final number of slimes.

Sample Input 1

10
aabbbbaaca

Sample Output 1

5

Ultimately, these slimes will fuse into abaca.

Sample Input 2

5
aaaaa

Sample Output 2

1

All the slimes will fuse into one.

Sample Input 3

20
xxzaffeeeeddfkkkkllq

Sample Output 3

10


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

n=io.read("*n","*l")
l={}
for i=1,n do
    l[i]=io.read("*n")
end
table.sort(l)
counter=0
for i=n,3,-1 do
    large=l[i]
    for j=i-1,2,-1 do
        middle=l[j]
        if middle*2<=large then
            break
        end
        local smallmin=upper_bound(large-middle,l)
        if smallmin<j then
            counter=counter+j-smallmin
        end
    end
end
print(counter)

Score : 400 points

Problem Statement

Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.

He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

a < b + c

b < c + a

c < a + b

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

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

1 \leq L_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23


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

n=io.read("*n","*l")
l={}
for i=1,n do
    l[i]=io.read("*n")
end
table.sort(l)
counter=0
for i=n,3,-1 do
    large=l[i]
    for j=i-1,2,-1 do
        middle=l[j]
        if middle*2<=large then
            break
        end
        local smallmin=upper_bound(large-middle,l)
        print(smallmin)
        if smallmin<j then
            counter=counter+j-smallmin
        end
    end
end
print(counter)


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
--
-- 1 <= input to f <= n
local function find_min_true(n, f)
    local function loop(i, j)
        if i == j then
            assert(i >= 1 and i <= n + 1)
            return i
        end
        local h = (i + j) // 2
        assert(h >= 1 and h <= n)
        if f(h) then
            return loop(i, h)
        else
            return loop(h + 1, j)
        end
    end
    return loop(1, n + 1)
end
--
local N = read.n()
local L = read.N(N)
table.sort(L)
local ans = 0
for i=1,N-2 do
    local a = L[i]
    for j=i+1,N-1 do
        local b = L[j]
        local function count()
            local function f(x)
                x = x + j -- [1,N-j] --> [j+1,N]
                local c = L[x]
                return c >= a + b
            end
            return find_min_true(N-j, f) - 1
        end
        ans = ans + count()
    end
end
print(ans)


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

local n, m, l = io.read("*n", "*n", "*n")
local edge = {}
for i = 1, n do
  edge[i] = {}
end
for i = 1, m do
  local a, b, c = io.read("*n", "*n", "*n")
  if c <= l then
    edge[a][b] = c
    edge[b][a] = c
  end
end
local len = {}
local inf = 301 * 1000000000
for i = 1, n do
  len[i] = inf
end
local function lessthan(x, y, cost)
  return len[x] + cost < len[y]
end
local function merge(x, y)
  if n < x then return y end
  if n < y then return x end
  return lessthan(x, y, 0) and x or y
end
local st = SegTree.new(n, merge, n + 1)
for i = 1, n do st:setValue(i, i) end
local alllen = {}

local function solve(start_pos)
  alllen[start_pos] = {}
  for i = 1, n do
    len[i] = inf
    alllen[start_pos][i] = 301
  end
  len[start_pos] = 0
  st:updateAll()
  local asked = {}
  for i = 1, n do
    asked[i] = false
  end
  for tankuse = 0, n - 2 do
    local nxtstt = {}
    for _u = 1, n do
      local src = st.stage[1][1]
      if inf <= len[src] then break end
      asked[src] = true
      if alllen[start_pos][src] == 301 then
        alllen[start_pos][src] = tankuse
      end
      for dst, cost in pairs(edge[src]) do
        if alllen[start_pos][dst] == 301 and not asked[dst] and lessthan(src, dst, cost) then
          if len[src] + cost <= l then
            len[dst] = len[src] + cost
            st:setValue(dst, dst)
          else
            table.insert(nxtstt, src)
          end
        end
      end
      len[src] = inf
      st:setValue(src, src)
    end
    for i = 1, #nxtstt do
      local j = nxtstt[i]
      len[j] = 0
      asked[j] = false
      st:setValue(j, j)
    end
  end
end

for i = 1, n do
  solve(i)
end

local q = io.read("*n")
for i = 1, q do
  local s, t = io.read("*n", "*n")
  print(alllen[s][t] < 301 and alllen[s][t] or -1)
end

Score : 500 points

Problem Statement

There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.

Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.

Process the following Q queries:

The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town s_i to Town t_i. If Town t_i is unreachable, print -1.

Constraints

All values in input are integers.

2 \leq N \leq 300

0 \leq M \leq \frac{N(N-1)}{2}

1 \leq L \leq 10^9

1 \leq A_i, B_i \leq N

A_i \neq B_i

\left(A_i, B_i\right) \neq \left(A_j, B_j\right) (if i \neq j)

\left(A_i, B_i\right) \neq \left(B_j, A_j\right) (if i \neq j)

1 \leq C_i \leq 10^9

1 \leq Q \leq N\left(N-1\right)

1 \leq s_i, t_i \leq N

s_i \neq t_i

\left(s_i, t_i\right) \neq \left(s_j, t_j\right) (if i \neq j)

Input

Input is given from Standard Input in the following format:

N M L
A_1 B_1 C_1
:
A_M B_M C_M
Q
s_1 t_1
:
s_Q t_Q

Output

Print Q lines.

The i-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town s_i to Town t_i. If Town t_i is unreachable, the line should contain -1 instead.

Sample Input 1

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

Sample Output 1

0
1

To travel from Town 3 to Town 2, we can use the second road to reach Town 2 without fueling the tank on the way.

To travel from Town 1 to Town 3, we can first use the first road to get to Town 2, full the tank, and use the second road to reach Town 3.

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

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

Sample Output 3

0
0
1
2
0
0
1
2
0
0
0
1
1
1
0
0
2
2
1
0


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

local n, m, l = io.read("*n", "*n", "*n")
local edge = {}
for i = 1, n do
  edge[i] = {}
end
for i = 1, m do
  local a, b, c = io.read("*n", "*n", "*n")
  if c <= l then
    edge[a][b] = c
    edge[b][a] = c
  end
end
local len = {}
local inf = 301 * 1000000000
for i = 1, n do
  len[i] = inf
end
local function lessthan(x, y, cost)
  return len[x] + cost < len[y]
end
local function merge(x, y)
  if n < x then return y end
  if n < y then return x end
  return lessthan(x, y, 0) and x or y
end
local st = SegTree.new(n, merge, n + 1)
for i = 1, n do st:setValue(i, i) end
local alllen = {}

local function solve(start_pos)
  alllen[start_pos] = {}
  for i = 1, n do
    len[i] = inf
    alllen[start_pos][i] = 301
  end
  len[start_pos] = 0
  st:updateAll()
  for tankuse = 0, n - 2 do
    local asked = {}
    for i = 1, n do
      asked[i] = false
    end
    for _u = 1, n do
      local src = st.stage[1][1]
      if inf <= len[src] then break end
      asked[src] = true
      if alllen[start_pos][src] == 301 then
        alllen[start_pos][src] = tankuse
      end
      for dst, cost in pairs(edge[src]) do
        if not asked[dst] and len[src] + cost <= l and lessthan(src, dst, cost) then
          len[dst] = len[src] + cost
          st:setValue(dst, dst)
        end
      end
      len[src] = inf
      st:setValue(src, src)
    end
    for i = 1, n do
      if asked[i] then
        len[i] = 0
        st:setValue(i, i)
      end
    end
  end
end

for i = 1, n do
  solve(i)
end

local q = io.read("*n")
for i = 1, q do
  local s, t = io.read("*n", "*n")
  print(alllen[s][t] < 301 and alllen[s][t] or -1)
end


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

local n, m, l = io.read("*n", "*n", "*n")
local edge = {}
for i = 1, n do
  edge[i] = {}
end
for i = 1, m do
  local a, b, c = io.read("*n", "*n", "*n")
  if c <= l then
    edge[a][b] = c
    edge[b][a] = c
  end
end
local tanklen = {}
local remlen = {}
local reallen = {}
local inf = 301 * 1000000000
for i = 1, n do
  tanklen[i] = 301
  remlen[i] = 0
  reallen[i] = inf
end
local function lessthan(x, y, cost)
  return reallen[x] + cost < reallen[y]
end
local function merge(x, y)
  if n < x then return y end
  if n < y then return x end
  return lessthan(x, y, 0) and x or y
end
local st = SegTree.new(n, merge, n + 1)
for i = 1, n do st:setValue(i, i) end
local alllen = {}
local function solve(start_pos)
  alllen[start_pos] = {}
  local asked = {}
  for i = 1, n do
    asked[i] = false
    tanklen[i] = 301
    remlen[i] = l
    reallen[i] = inf
  end
  tanklen[start_pos] = 0
  reallen[start_pos] = 0
  st:updateAll()
  for _u = 1, n do
    local src = st.stage[1][1]
    if src == n + 1 then break end
    if tanklen[src] == 301 then break end
    asked[src] = true
    alllen[start_pos][src] = tanklen[src]
    for dst, cost in pairs(edge[src]) do
      if not asked[dst] and lessthan(src, dst, cost) then
        reallen[dst] = reallen[src] + cost
        tanklen[dst] = tanklen[src]
        remlen[dst] = remlen[src] - cost
        if remlen[dst] < 0 then
          tanklen[dst] = tanklen[dst] + 1
          remlen[dst] = l - cost
        end
        st:setValue(dst, dst)
      end
    end
    reallen[src] = inf
    st:setValue(src, src)
  end
end

for i = 1, n do
  solve(i)
end

local q = io.read("*n")
for i = 1, q do
  local s, t = io.read("*n", "*n")
  print(alllen[s][t] < 301 and alllen[s][t] or -1)
end


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

local n, m, l = io.read("*n", "*n", "*n")
local edge = {}
for i = 1, n do
  edge[i] = {}
end
for i = 1, m do
  local a, b, c = io.read("*n", "*n", "*n")
  if c <= l then
    edge[a][b] = c
    edge[b][a] = c
  end
end
local tanklen = {}
local remlen = {}
local reallen = {}
local inf = 301 * 1000000000
for i = 1, n do
  tanklen[i] = 301
  remlen[i] = 0
  reallen[i] = inf
end
local function lessthan(x, y, cost)
  return reallen[x] + cost < reallen[y]
end
local function merge(x, y)
  if n < x then return y end
  if n < y then return x end
  return lessthan(x, y, 0) and x or y
end
local st = SegTree.new(n, merge, n + 1)
for i = 1, n do st:setValue(i, i) end
local alllen = {}
local function solve(start_pos)
  alllen[start_pos] = {}
  local asked = {}
  for i = 1, n do
    asked[i] = false
    tanklen[i] = 301
    remlen[i] = l
    reallen[i] = inf
  end
  tanklen[start_pos] = 0
  reallen[start_pos] = 0
  st:updateAll()
  for _u = 1, n do
    local src = st.stage[1][1]
    asked[src] = true
    alllen[start_pos][src] = tanklen[src]
    for dst, cost in pairs(edge[src]) do
      if not asked[dst] and lessthan(src, dst, cost) then
        reallen[dst] = reallen[src] + cost
        tanklen[dst] = tanklen[src]
        remlen[dst] = remlen[src] - cost
        if remlen[dst] < 0 then
          tanklen[dst] = tanklen[dst] + 1
          remlen[dst] = l - cost
        end
        st:setValue(dst, dst)
      end
    end
    reallen[src] = inf
    st:setValue(src, src)
  end
end

for i = 1, n do
  solve(i)
end

local q = io.read("*n")
for i = 1, q do
  local s, t = io.read("*n", "*n")
  print(alllen[s][t] < 301 and alllen[s][t] or -1)
end


local s = io.read()
local a,b = tonumber(s),tonumber(s)//2 + tonumber(s) % 2
local result = b / a
print(result)

Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000


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


local n = io.read("*n")
ev = n // 2
od = n - ev
print(string.format("%.10f", od / n))


local x,y = io.read("*l"):match("(%d+).(%d+)")
local arr = {}
local result = 0
for _ in io.read("*l"):gmatch("%d+") do
  table.insert(arr,tonumber(_))
end
table.sort(arr)
for i = 1,tonumber(x) do
  if arr[i] >= tonumber(y) then
    result = #arr - i + 1
    break
  end
end
print(result)

Score : 200 points

Problem Statement

N friends of Takahashi has come to a theme park.

To ride the most popular roller coaster in the park, you must be at least K centimeters tall.

The i-th friend is h_i centimeters tall.

How many of the Takahashi's friends can ride the roller coaster?

Constraints

1 \le N \le 10^5

1 \le K \le 500

1 \le h_i \le 500

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the number of people among the Takahashi's friends who can ride the roller coaster.

Sample Input 1

4 150
150 140 100 200

Sample Output 1

2

Two of them can ride the roller coaster: the first and fourth friends.

Sample Input 2

1 500
499

Sample Output 2

0

Sample Input 3

5 1
100 200 300 400 500

Sample Output 3

5


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

Score : 300 points

Problem Statement

Takahashi is a teacher responsible for a class of N students.

The students are given distinct student numbers from 1 to N.

Today, all the students entered the classroom at different times.

According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).

From these records, reconstruct the order in which the students entered the classroom.

Constraints

1 \le N \le 10^5

1 \le A_i \le N

A_i \neq A_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print the student numbers of the students in the order the students entered the classroom.

Sample Input 1

3
2 3 1

Sample Output 1

3 1 2

First, student number 3 entered the classroom.

Then, student number 1 entered the classroom.

Finally, student number 2 entered the classroom.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

1 2 3 4 5

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

8 2 4 5 6 7 3 1


local x = io.read("*l"):match("(%d+)")
local arr = {}
local a,b
local result = 0
for i = 1,tonumber(x) do
  arr[i] = 1
end
b = 0
for _ in io.read("*l"):gmatch("%d+") do
  b = b + 1
  a = tonumber(_)
  arr[a] = b
end
local xx = tonumber(x)
for i = 1,xx do
  io.write(arr[i])
  if i == xx then
    break
  end
  io.write(" ")
end


local function gcd(a,b)
    if b>0 then
        return gcd(b,a%b)
    else
        return a
    end
end

local x=gcd(io.read("n","n"))

local counter=1
for i=2,math.sqrt(x) do
    if x%i==0 then
        while x%i==0 do
            x=math.floor(x/i)
        end
        counter=counter+1
    end
end
print(x~=1 and counter+1 or counter)

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


local function gcd(a,b)
    if b>0 then
        return gcd(b,a%b)
    else
        return a
    end
end

local x=gcd(io.read("n","n"))

local counter=1
for i=2,x do
    if x==1 then
        break
    end
    if x%i==0 then
        while x%i==0 do
            x=x//i
        end
        counter=counter+1
    end
end
print(counter)


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

local n, m = io.read("*n", "*n")
local longest_len = {}
local edge = {}
local invedge = {}
local updated = {}
local startcand = {}
for i = 1, n + 1 do
  longest_len[i] = -1
  edge[i] = {}
  invedge[i] = {}
  updated[i] = false
  startcand[i] = true
end
for i = 1, m do
  local a, b = io.read("*n", "*n")
  edge[a][b] = true
  invedge[b][a] = true
  startcand[b] = false
end
local function getmax(a, b)
  if updated[a] and updated[b] then
    return longest_len[a] < longest_len[b] and b or a
  elseif updated[a] then return a
  elseif updated[b] then return b
  else return n + 1
  end
end
-- find loop candidate
local st = SegTree.new(n, getmax, n + 1)
for i = 1, n do
  longest_len[i] = 0
  updated[i] = true
end
st:updateAll()
while true do
  local src = st:top()
  if src == n + 1 then break end
  for dst, _u in pairs(edge[src]) do
    if longest_len[dst] < 0 or longest_len[dst] < longest_len[src] + 1 then
      if longest_len[dst] < n then
        longest_len[dst] = longest_len[src] + 1
        updated[dst] = true
        st:update(dst)
      end
    end
  end
  updated[src] = false
  st:update(src)
end

local loopCandidates = {}
for i = 1, n do
  if n <= longest_len[i] then
    loopCandidates[i] = true
  end
end
-- remove no-loop points from loop candidate points
while true do
  local removed = false
  for src, _u in pairs(loopCandidates) do
    local f = false
    for dst, _u2 in pairs(edge[src]) do
      if loopCandidates[dst] then
        f = true
        break
      end
    end
    if not f then loopCandidates[src], removed = nil, true break end
  end
  if not removed then break end
end

-- remove all no-loop edges
for src, _u in pairs(loopCandidates) do
  for dst, _u2 in pairs(edge[src]) do
    if not loopCandidates[dst] then edge[src][dst] = nil end
  end
  for dst, _u2 in pairs(invedge[src]) do
    if not loopCandidates[dst] then invedge[src][dst] = nil end
  end
end

-- find first length and second length from certain point
local loop_len = {}
local loop_started = {}
for src, _u in pairs(loopCandidates) do
  loop_len[src] = {-1, -1}
  loop_started[src] = false
end
if next(loopCandidates) then
  local src = next(loopCandidates)
  loop_len[src][1] = 0
  updated[src] = true
end

local function getlooptask(a, b)
  if updated[a] and updated[b] then
    if loop_len[a][2] < 0 and loop_len[b][2] < 0 then
      return loop_len[a][1] < loop_len[b][1] and a or b
    elseif loop_len[a][2] < 0 then return a
    elseif loop_len[b][2] < 0 then return b
    else
      return loop_len[a][2] < loop_len[b][2] and a or b
    end
  elseif updated[a] then return a
  elseif updated[b] then return b
  else return n + 1
  end
end

st.func = getlooptask
st:updateAll()

while true do
  local src = st:top()
  if src == n + 1 then break end
  for dst, _u in pairs(edge[src]) do
    if loop_started[dst] then
      if loop_started[src] then
        if loop_len[dst][2] < 0 or loop_len[src][2] + 1 < loop_len[dst][2] then
          loop_len[dst][2] = loop_len[src][2] + 1
          updated[dst] = true
          st:update(dst)
        end
      else
        if loop_len[dst][2] < 0 or loop_len[src][1] + 1 < loop_len[dst][2] then
          loop_len[dst][2] = loop_len[src][1] + 1
          updated[dst] = true
          st:update(dst)
        end
      end
    else
      if loop_len[dst][1] < 0 or loop_len[src][1] + 1 < loop_len[dst][1] then
        loop_len[dst][1] = loop_len[src][1] + 1
        updated[dst] = true
        st:update(dst)
      end
    end
  end
  loop_started[src] = true
  updated[src] = false
  st:update(src)
end

-- get start of shortest loop
local short_loop_start = false
local short_loop_len = false
for src, v in pairs(loop_len) do
  local len = v[2] - v[1]
  if 0 < len then
    if not short_loop_len or len < short_loop_len then
      short_loop_start, short_loop_len = src, len
    end
  end
end
if short_loop_start then
  local ans = {short_loop_start}
  while true do
    local dst = ans[#ans]
    local dstlen = #ans == 1 and loop_len[dst][2] or loop_len[dst][1]
    local f = false
    for src, _u in pairs(invedge[dst]) do
      local srclen = loop_len[src][1]
      if loop_len[src][2] - srclen == short_loop_len and srclen + 1 == dstlen then
        table.insert(ans, src)
        f = true
        break
      end
    end
    if not f then break end
  end
  table.remove(ans)
  print(#ans)
  print(table.concat(ans, "\n"))
else
  print(-1)
end

Score : 600 points

Problem Statement

Given is a directed graph G with N vertices and M edges.

The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i.

It is guaranteed that the graph contains no self-loops or multiple edges.

Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph.

Here the null graph is not considered as a subgraph.

Notes

For a directed graph G = (V, E), we call a directed graph G' = (V', E') satisfying the following conditions an induced subgraph of G:

V' is a (non-empty) subset of V.

E' is the set of all the edges in E that have both endpoints in V'.

Constraints

1 \leq N \leq 1000

0 \leq M \leq 2000

1 \leq A_i,B_i \leq N

A_i \neq B_i

All pairs (A_i, B_i) are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
:
A_M B_M

Output

If there is no induced subgraph of G that satisfies the condition, print -1.
Otherwise, print an induced subgraph of G that satisfies the condition, in the following format:

K
v_1
v_2
:
v_K

This represents the induced subgraph of G with K vertices whose vertex set is \{v_1, v_2, \ldots, v_K\}. (The order of v_1, v_2, \ldots, v_K does not matter.)
If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted.

Sample Input 1

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

Sample Output 1

3
1
2
4

The induced subgraph of G whose vertex set is \{1, 2, 4\} has the edge set \{(1, 2), (2, 4), (4, 1)\}. The in-degree and out-degree of every vertex in this graph are both 1.

Sample Input 2

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

Sample Output 2

-1

There is no induced subgraph of G that satisfies the condition.

Sample Input 3

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

Sample Output 3

4
2
3
4
5


local n, m = io.read("*n", "*n")
local edge = {}
local edge2 = {}
local edge3 = {}
for i = 1, n do edge2[i] = {} edge3[i] = {} end
for i = 1, m do
  local a, b = io.read("*n", "*n")
  table.insert(edge, {a, b})
  table.insert(edge2[a], b)
  table.insert(edge3[b], a)
end
local len = {}
local inf = 1010
for i = 1, n do len[i] = -inf end
len[1] = 0
local lim = n + 4
for i = 1, lim do
  for j = 1, m do
    local src, dst, c = edge[j][1], edge[j][2], 1
    if len[src] ~= -inf and len[dst] < len[src] + c then
      len[dst] = len[src] + c
      if i == lim then
        len[dst] = inf
      end
    end
  end
end
for i = 1, lim do
  for j = 1, m do
    local src, dst = edge[j][1], edge[j][2]
    if len[src] == inf then
      len[dst] = inf
    end
  end
end
local startpos = 0
local scand = {}
local scflag = {}
local scasked = {}
for i = 1, n do
  if len[i] == inf then
    table.insert(scand, i)
    scflag[i] = true
  else
    scflag[i] = false
  end
  scasked[i] = false
end
while 0 == startpos and 0 < #scand do
  local sc = scand[#scand]
  table.remove(scand)
  scflag[sc] = false
  scasked[sc] = true
  for i = 1, #edge3[sc] do
    local p = edge3[sc][i]
    if scasked[p] then
      startpos = p
      break
    elseif len[p] == inf then
      if not scflag[p] then
        table.insert(scand, p)
        scflag[p] = true
      end
    end
  end
end
if startpos == 0 then
  print(-1)
else
  local tasks = {startpos}
  local asked = {}
  for i = 1, n do
    asked[i] = false
  end
  local done = false
  while 0 < #tasks do
    local src = tasks[#tasks]
    table.remove(tasks)
    asked[src] = true
    while 0 < #edge2[src] do
      local dst = edge2[src][#edge2[src]]
      if dst == startpos then
        table.insert(tasks, src)
        for i = #tasks, 1, -1 do
          if tasks[i] == startpos then
            print(#tasks - i + 1)
            for j = i, #tasks do
              print(tasks[j])
            end
            break
          end
        end
        done = true
      elseif not asked[dst] then
        table.insert(tasks, src)
        table.insert(tasks, dst)
        table.remove(edge2[src])
        break
      else
        table.remove(edge2[src])
      end
      if done then break end
    end
    if done then break end
  end
end


local n, m = io.read("*n", "*n")
local edge = {}
local edge2 = {}
local edge3 = {}
for i = 1, n do edge2[i] = {} edge3[i] = {} end
for i = 1, m do
  local a, b = io.read("*n", "*n")
  table.insert(edge, {a, b})
  table.insert(edge2[a], b)
  table.insert(edge3[b], a)
end
local len = {}
local inf = 1010
for i = 1, n do len[i] = -inf end
len[1] = 0
local lim = n + 4
for i = 1, lim do
  for j = 1, m do
    local src, dst, c = edge[j][1], edge[j][2], 1
    if len[src] ~= -inf and len[dst] < len[src] + c then
      len[dst] = len[src] + c
      if i == lim then
        len[dst] = inf
      end
    end
  end
end
for i = 1, lim do
  for j = 1, m do
    local src, dst = edge[j][1], edge[j][2]
    if len[src] == inf then
      len[dst] = inf
    end
  end
end
local startpos = 0
local scand = {}
local scflag = {}
local scasked = {}
for i = 1, n do
  if len[i] == inf then
    table.insert(scand, i)
    scflag[i] = true
  else
    scflag[i] = false
  end
  scasked[i] = false
end
while 0 == startpos and 0 < #scand do
  local sc = scand[#scand]
  table.remove(scand)
  scflag[sc] = false
  scasked[sc] = true
  for i = 1, #edge3[sc] do
    local p = edge3[sc][i]
    if scasked[p] then
      startpos = p
      break
    else
      if not scflag[p] then
        table.insert(scand, p)
        scflag[p] = true
      end
    end
  end
end
if startpos == 0 then
  print(-1)
else
  local tasks = {startpos}
  local asked = {}
  for i = 1, n do
    asked[i] = false
  end
  local done = false
  while 0 < #tasks do
    local src = tasks[#tasks]
    table.remove(tasks)
    asked[src] = true
    while 0 < #edge2[src] do
      local dst = edge2[src][#edge2[src]]
      if dst == startpos then
        table.insert(tasks, src)
        for i = #tasks, 1, -1 do
          if tasks[i] == startpos then
            print(#tasks - i + 1)
            for j = i, #tasks do
              print(tasks[j])
            end
            break
          end
        end
        done = true
      elseif not asked[dst] then
        table.insert(tasks, src)
        table.insert(tasks, dst)
        table.remove(edge2[src])
        break
      else
        table.remove(edge2[src])
      end
      if done then break end
    end
    if done then break end
  end
end


local n, m = io.read("*n", "*n")
local edge = {}
local edge2 = {}
local edge3 = {}
for i = 1, n do edge2[i] = {} edge3[i] = {} end
for i = 1, m do
  local a, b = io.read("*n", "*n")
  table.insert(edge, {a, b})
  table.insert(edge2[a], b)
  table.insert(edge3[b], a)
end
local len = {}
local inf = 1010
for i = 1, n do len[i] = -inf end
len[1] = 0
local lim = n + 4
for i = 1, lim do
  for j = 1, m do
    local src, dst, c = edge[j][1], edge[j][2], 1
    if len[src] ~= -inf and len[dst] < len[src] + c then
      len[dst] = len[src] + c
      if i == lim then
        len[dst] = inf
      end
    end
  end
end
for i = 1, lim do
  for j = 1, m do
    local src, dst = edge[j][1], edge[j][2]
    if len[src] == inf then
      len[dst] = inf
    end
  end
end
local startpos = 0
local scand = {}
local scflag = {}
local scasked = {}
for i = 1, n do
  if len[i] == inf then
    table.insert(scand, i)
    scflag[i] = true
  else
    scflag[i] = false
  end
  scasked[i] = false
end
while 0 == startpos and 0 < #scand do
  local sc = scand[#scand]
  table.remove(scand)
  scflag[sc] = false
  scasked[sc] = true
  for i = 1, #edge3[sc] do
    local p = edge3[sc][i]
    if scasked[p] then
      startpos = p
      break
    elseif len[p] ~= inf then
      startpos = sc
      break
    else
      if not scflag[p] then
        table.insert(scand, p)
        scflag[p] = true
      end
    end
  end
end
if startpos == 0 then
  print(-1)
else
  local tasks = {startpos}
  local asked = {}
  for i = 1, n do
    asked[i] = false
  end
  local done = false
  while 0 < #tasks do
    local src = tasks[#tasks]
    table.remove(tasks)
    asked[src] = true
    while 0 < #edge2[src] do
      local dst = edge2[src][#edge2[src]]
      if dst == startpos then
        table.insert(tasks, src)
        for i = #tasks, 1, -1 do
          if tasks[i] == startpos then
            print(#tasks - i + 1)
            for j = i, #tasks do
              print(tasks[j])
            end
            break
          end
        end
        done = true
      elseif not asked[dst] then
        table.insert(tasks, src)
        table.insert(tasks, dst)
        table.remove(edge2[src])
        break
      else
        table.remove(edge2[src])
      end
      if done then break end
    end
    if done then break end
  end
end


local s=io.read()
if s=="Sunny"then
  print("Cloudy")
elseif s=="Cloudy"then
  print("Rainy")
else
  print("Sunny")
end

Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


local t = {"Sunny", "Cloudy", "Rainy"}
s = io.read()

local pos = 0
for i = 1, 3 do
    if t[i] == s then
        pos = i
        break
    end
end

print(t[pos%3+1])


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, string.sub(k, i, i)) end local r = io.read local u = table.unpack return function() return r(u(a)) end end})
local S = read.l()
local T = {}
T.Sunny = "Cloudy"
T.Cloudy= "Rainy"
T.Rainy = "Sunny"
print(T[S])


function split(s, c)
  if string.find(s, c) == nil then
    return { s }
  end

  local cs = {}

  local lastPos = 0
  for part, p in string.gmatch(s, "(.-)" .. c .. "()") do
    table.insert(cs, part)
    lastPos = p
  end

  table.insert(cs, string.sub(s, lastPos))

  return cs
end

n=io.read("*n")

print(n*n*n)

Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, string.sub(k, i, i)) end local r = io.read local u = table.unpack return function() return r(u(a)) end end})
local A = read.n()
print(A*A*A)


local read = setmetatable({}, {__index = function(t, k) local a = {} for i=1,#k do table.insert(a, string.sub(k, i, i)) end local r = io.read local u = table.unpack return function() return r(u(a)) end end})
local N = read.n()
local A, B, C = {}, {}, {}
for i=1,N do
    A[i] = read.n()
end
for i=1,N do
    B[i] = read.n()
end
for i=1,N-1 do
    C[i] = read.n()
end

local ans = 0
local prev = nil
for i=1,N do
    ans = ans + B[A[i]]
    if prev and A[i] == prev + 1 then
        ans = ans + C[prev]
    end
    prev = A[i]
end
print(ans)

Score : 200 points

Problem Statement

Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.

The i-th dish (1 \leq i \leq N) he ate was Dish A_i.

When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.

Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.

Find the sum of the satisfaction points he gained.

Constraints

All values in input are integers.

2 \leq N \leq 20

1 \leq A_i \leq N

A_1, A_2, ..., A_N are all different.

1 \leq B_i \leq 50

1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

Output

Print the sum of the satisfaction points Takahashi gained, as an integer.

Sample Input 1

3
3 1 2
2 5 4
3 6

Sample Output 1

14

Takahashi gained 14 satisfaction points in total, as follows:

First, he ate Dish 3 and gained 4 satisfaction points.

Next, he ate Dish 1 and gained 2 satisfaction points.

Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.

Sample Input 2

4
2 3 4 1
13 5 8 24
45 9 15

Sample Output 2

74

Sample Input 3

2
1 2
50 50
50

Sample Output 3

150


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

A = {}
for i = 1, N do
    if i == 1 then
        A[i] = B[i]
    elseif i == N then
        A[i] = B[i-1]
    else
        A[i] = math.min(B[i-1], B[i])
    end
end

sum = 0
for i = 1, N do
    sum = sum + A[i]
end
print(sum)

Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53


function split(s, c)
  if string.find(s, c) == nil then
    return { s }
  end

  local cs = {}

  local lastPos = 0
  for part, p in string.gmatch(s, "(.-)" .. c .. "()") do
    table.insert(cs, part)
    lastPos = p
  end

  table.insert(cs, string.sub(s, lastPos))

  return cs
end

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

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

ans=0

a1=0
a2=0

for i=1, n-1 do
  a1=a2
  if i == 1 then
    a1=b[i]
    a2=b[i]
  end
  if b[i+1] == nil then
    a2=b[i]
  elseif b[i] > b[i+1] then
    a2=b[i+1]
  end

  ans = ans + a1
end

ans = ans + a2

print(ans)


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

-- find smallest x where
-- left <= x
-- val <= f[left:x]
-- if not exist then return right + 1
SegTree.right_bound = function(self, val, left, right)
  local ret, retpos = self.emptyvalue, left - 1
  local t1, t2, t3 = {1}, {left}, {right}
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    while (l - 1) % sz ~= 0 or r + 1 - l < sz do
      stage = stage + 1
      sz = self.size[stage]
    end
    local tmp = self.func(ret, self.stage[stage][mce(l / sz)])
    if tmp < val then
      ret, retpos = tmp, l + sz - 1
      if retpos == right then break end
      if l + sz <= r then table.insert(t1, 1) table.insert(t2, l + sz) table.insert(t3, r) end
    else
      if sz ~= 1 then table.insert(t1, stage + 1) table.insert(t2, l) table.insert(t3, l + sz - 2) end
    end
  end
  return retpos + 1
end

-- find largest x where
-- x <= right
-- val <= f[x:right]
-- if not exist then return left - 1
SegTree.left_bound = function(self, val, left, right)
  local ret, retpos = self.emptyvalue, right + 1
  local t1, t2, t3 = {1}, {left}, {right}
  while 0 < #t1 do
    local stage, l, r = t1[#t1], t2[#t1], t3[#t1]
    table.remove(t1) table.remove(t2) table.remove(t3)
    local sz = self.size[stage]
    while r % sz ~= 0 or r + 1 - l < sz do
      stage = stage + 1
      sz = self.size[stage]
    end
    local tmp = self.func(ret, self.stage[stage][mfl(r / sz)])
    if tmp < val then
      ret, retpos = tmp, r - sz + 1
      if l + sz <= r then table.insert(t1, 1) table.insert(t2, l) table.insert(t3, r - sz) end
    else
      if sz ~= 1 then table.insert(t1, stage + 1) table.insert(t2, r - sz + 2) table.insert(t3, r) end
    end
  end
  return retpos - 1
end

local n = io.read("*n")
local st = SegTree.new(n, mma, 0)
local t = {}
for i = 1, n do t[i] = 0 end
for i = 1, n do
  local a = io.read("*n")
  t[a] = i
  st:setValue(i, a, true)
end
st:updateAll()
local retary = {}
for i = 1, n - 1 do
  local pos = t[i]
  local left1, left2 = 0, 0
  local right1, right2 = n + 1, n + 1
  if 1 < pos then
    left1 = st:left_bound(i, 1, pos - 1)
    if 1 < left1 then
      left2 = st:left_bound(i, 1, left1 - 1)
    end
  end
  if pos < n then
    right1 = st:right_bound(i, pos + 1, n)
    if right1 < n then
      right2 = st:right_bound(i, right1 + 1, n)
    end
  end
  local tmp = 0
  if 0 < left1 then
    local l_range = left1 - left2
    local r_range = right1 - pos
    tmp = tmp + l_range * r_range
  end
  if right1 <= n then
    local l_range = pos - left1
    local r_range = right2 - right1
    tmp = tmp + l_range * r_range
  end
  retary[i] = tmp
end

local ret = 0LL
for i = 1, n - 1 do
  ret = ret + retary[i] * i
end
local str = tostring(ret):gsub("LL", "")
print(str)

Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136


local N = io.read("n")
local S = {}
for i=1,2^N do
    local s = io.read("n")
    S[i] = s
end
table.sort(S, function(x,y)return x>y end)
local family = {}
family[1] = S[1]
S[1] = -1
for n=1,N do
    local parents = {table.unpack(family)}
    table.sort(parents, function(x,y)return x>y end)
    local todo = 1
    local sidx = 1
    while todo <= #parents and sidx <= #S do
        if S[sidx] ~= -1 and S[sidx] < parents[todo] then
            family[#family + 1] = S[sidx]
            todo = todo + 1
            S[sidx] = -1
        end
        sidx = sidx + 1
    end
    if todo <= #parents then
        print("No")
        return
    end
end
print("Yes")

Score : 600 points

Problem Statement

We have one slime.

You can set the health of this slime to any integer value of your choice.

A slime reproduces every second by spawning another slime that has strictly less health. You can freely choose the health of each new slime. The first reproduction of our slime will happen in one second.

Determine if it is possible to set the healths of our first slime and the subsequent slimes spawn so that the multiset of the healths of the 2^N slimes that will exist in N seconds equals a multiset S.

Here S is a multiset containing 2^N (possibly duplicated) integers: S_1,~S_2,~...,~S_{2^N}.

Constraints

All values in input are integers.

1 \leq N \leq 18

1 \leq S_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
S_1 S_2 ... S_{2^N}

Output

If it is possible to set the healths of the first slime and the subsequent slimes spawn so that the multiset of the healths of the 2^N slimes that will exist in N seconds equals S, print Yes; otherwise, print No.

Sample Input 1

2
4 2 3 1

Sample Output 1

Yes

We will show one way to make the multiset of the healths of the slimes that will exist in 2 seconds equal to S.

First, set the health of the first slime to 4.

By letting the first slime spawn a slime whose health is 3, the healths of the slimes that exist in 1 second can be 4,~3.

Then, by letting the first slime spawn a slime whose health is 2, and letting the second slime spawn a slime whose health is 1, the healths of the slimes that exist in 2 seconds can be 4,~3,~2,~1, which is equal to S as multisets.

Sample Input 2

2
1 2 3 1

Sample Output 2

Yes

S may contain multiple instances of the same integer.

Sample Input 3

1
1 1

Sample Output 3

No

Sample Input 4

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

Sample Output 4

No


s=io.read():match("%w+")
t=io.read():match("%w+")
cnt=0
for i=1,3,1 do
  if s:sub(i,i)==t:sub(i,i)then
    cnt=cnt+1
  end
end
print(cnt)

Score : 100 points

Problem Statement

You will be given a string S of length 3 representing the weather forecast for three days in the past.

The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

You will also be given a string T of length 3 representing the actual weather on those three days.

The i-th character (1 \leq i \leq 3) of S represents the actual weather on the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

Print the number of days for which the forecast was correct.

Constraints

S and T are strings of length 3 each.

S and T consist of S, C, and R.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the number of days for which the forecast was correct.

Sample Input 1

CSS
CSR

Sample Output 1

2

For the first day, it was forecast to be cloudy, and it was indeed cloudy.

For the second day, it was forecast to be sunny, and it was indeed sunny.

For the third day, it was forecast to be sunny, but it was rainy.

Thus, the forecast was correct for two days in this case.

Sample Input 2

SSR
SSR

Sample Output 2

3

Sample Input 3

RRR
SSS

Sample Output 3

0


function char(s, n)
  return string.sub(s, n, n)
end

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

ans=0

for i=1, 3 do
  if char(s, i) == char(t, i) then
    ans=ans+1
  end
end

print(ans)


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

local div_b = (b - 1) // a
print(((b - 1) % a == 0) and div_b or div_b + 1)

Score : 200 points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

2 \leq A \leq 20

1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

Sample Input 2

8 9

Sample Output 2

2

2 power strips, each with 8 sockets, extend the socket into 15 empty sockets.

Sample Input 3

8 8

Sample Output 3

1


local a,b = io.read("a"):match("(%d+).(%d+)")
a,b = tonumber(a) - 1,tonumber(b)
local count = 0
local loop = true
while loop do
  if b == 0 then
    break
  end
  count = count + 1
  if b <= a * count + 1 then
    loop = false
  end
end
print(count)


local a, b = io.read("*n", "*n")
if b == 1 then
  print(0)
else
  local c = 0
  local x = 1
  while x < b do
    x = x + (a - 1)
    c = c + 1
  end
  print(c)
end


n = io.read("*n")
n = 0LL + n
r = n * (n - 1) / 2LL
str = tostring(r):gsub("LL", "")
print(str)

Score : 400 points

Problem Statement

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

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

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

Constraints

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

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

2

Sample Output 1

1

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

Sample Input 2

13

Sample Output 2

78

Sample Input 3

1

Sample Output 3

0


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

Score : 500 points

Problem Statement

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

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

Each player plays at most one matches in a day.

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

Constraints

3 \leq N \leq 1000

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

A_{i, j} \neq i

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

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

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

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

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

Day 2: Player 1 vs Player 3

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

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.


local mod = 1000000007

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

local n = io.read("*n", "*l")
local s = io.read()
local depth = 0
local f = true
local ret = 1
for i = 1, 2 * n do
  if s:sub(i, i) == "B" then
    if depth % 2 == 0 then
      depth = depth + 1
    else
      ret = bmul(ret, depth)
      depth = depth - 1
    end
  else
    if depth % 2 == 0 then
      if depth == 0 then
        f = false
        break
      else
        ret = bmul(ret, depth)
        depth = depth - 1
      end
    else
      depth = depth + 1
    end
  end
end
if 0 ~= depth then f = false end
if f then
  for i = 1, n do
    ret = bmul(ret, i)
  end
else
  ret = 0
end
print(ret)

Score : 500 points

Problem Statement

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

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

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

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

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

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

Constraints

1 \leq N \leq 10^5

|S| = 2N

Each character of S is B or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

2
BWWB

Sample Output 1

4

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

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

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

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

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

Sample Input 2

4
BWBBWWWB

Sample Output 2

288

Sample Input 3

5
WWWWWWWWWW

Sample Output 3

0


local a,b = io.read("*l"),0
local c = io.read():gmatch("%d+")
for d in c do
  print(d)
  b = b + d^(-1)
end
print(b^(-1))

Score : 200 points

Problem Statement

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

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

Constraints

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

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

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

Sample Input 1

2
10 30

Sample Output 1

7.5

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

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

Sample Input 2

3
200 200 200

Sample Output 2

66.66666666666667

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

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

Sample Input 3

1
1000

Sample Output 3

1000

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

Printing +1000.0 and so on will also be accepted.


local n = io.read("*n")
local denom = 0
for i = 1, n do
  local a = io.read("*n")
  denom = denom + 1 / a
end
print(string.format("%.10f", 1 / denom))


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

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

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

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

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

local cur = 0
local ans = 0
local i = 1
while i <= #T do
    local c = T[i]
    local step = lookup[cur][c]
    --dbgpr(i, ans, c, cur, step)
    if step then
        ans = ans + step
        cur = cur + step
        i = i + 1
    elseif cur ~= 0 then
        ans = ans + (#S - cur)
        cur = 0
    else
        -- cur == 0
        print("-1")
        return
    end
end
print(ans)

Score : 500 points

Problem Statement

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

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

Notes

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

Constraints

1 \leq |s| \leq 10^5

1 \leq |t| \leq 10^5

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

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

Sample Input 1

contest
son

Sample Output 1

10

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

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

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

Sample Input 2

contest
programming

Sample Output 2

-1

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

Sample Input 3

contest
sentence

Sample Output 3

33

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


local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegTree = {}
SegTree.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = self.func(self.stage[i + 1][j * 2 - 1], self.stage[i + 1][j * 2])
    end
  end
end
SegTree.create = function(self, ary, func, emptyvalue)
  self.func, self.emptyvalue = func, emptyvalue
  local stagenum, mul = 1, 1
  self.cnt, self.stage, self.size = {1}, {{}}, {}
  while mul < #ary do
    mul, stagenum = mul * 2, stagenum + 1
    self.cnt[stagenum], self.stage[stagenum] = mul, {}
  end
  for i = 1, stagenum do self.size[i] = self.cnt[stagenum + 1 - i] end
  self.stagenum = stagenum
  for i = 1, #ary do self.stage[stagenum][i] = ary[i] end
  for i = #ary + 1, mul do self.stage[stagenum][i] = emptyvalue end
  self:updateAll()
end
SegTree.getTop = function(self)
  return self.stage[1][1]
end
SegTree.setValue = function(self, idx, value, silent)
  self.stage[self.stagenum][idx] = value
  if not silent then
    for i = self.stagenum - 1, 1, -1 do
      local dst = mce(idx / 2)
      local rem = dst * 4 - 1 - idx
      self.stage[i][dst] = self.func(self.stage[i + 1][idx], self.stage[i + 1][rem])
      idx = dst
    end
  end
end
SegTree.new = function(ary, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(ary, func, emptyvalue)
  return obj
end

local n = io.read("*n")
local a, b, stb = {}, {}, {}
for i = 1, n do
  a[i] = io.read("*n")
end
for i = 1, n do
  b[i] = io.read("*n")
  stb[i] = {i, b[i]}
end
local st = SegTree.new(stb, function(x, y)
  return x[2] < y[2] and y or x
end, {0, 0})

local rem = n
local cnt = 0
while 0 < rem do
  local top = st:getTop()
  local idx = top[1]
  if b[idx] == a[idx] then
    st:setValue(idx, {idx, 0})
    rem = rem - 1
  else
    cnt = cnt + 1
    local l, r = idx - 1, idx + 1
    if l == 0 then l = n end
    if r == n + 1 then r = 1 end
    if b[l] + b[r] < b[idx] then
      b[idx] = b[idx] - b[l] - b[r]
      st:setValue(idx, {idx, b[idx]})
    else
      cnt = -1
      break
    end
  end
end
print(cnt)

Score : 800 points

Problem Statement

There are N positive integers arranged in a circle.

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

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

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

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

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

Constraints

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

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3
1 1 1
13 5 7

Sample Output 1

4

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

Replace the second number with 3.

Replace the second number with 5.

Replace the third number with 7.

Replace the first number with 13.

Sample Input 2

4
1 2 3 4
2 3 4 5

Sample Output 2

-1

Sample Input 3

5
5 6 5 2 1
9817 1108 6890 4343 8704

Sample Output 3

25


a, b = io.read("*n", "*n")
print(math.max(a + b, a - b, a * b))

Score : 100 points

Problem Statement

We have two integers: A and B.

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

Constraints

All values in input are integers.

-100 \leq A,\ B \leq 100

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

-13 3

Sample Output 1

-10

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

Sample Input 2

1 -33

Sample Output 2

34

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

Sample Input 3

13 3

Sample Output 3

39

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


local a, b = string.match(io.read(), "([-]?%d+) ([-]?%d+)");
a, b = tonumber(a), tonumber(b);
local add, sub, mul = a + b, a - b, a * b;
print(math.max(add, sub, mul))


n=io.read("*n","*l")
counter={}
for i=1,n do
    s=io.read()
    t={}
    for i=1,10 do
        table.insert(t, s:sub(i,i))
        table.sort(t)
    end
    s_=table.concat(t)
    if not counter[s_] then
        counter[s_]=1
    else
        counter[s_]=counter[s_]+1
    end
end

total=0
for k,v in pairs(counter) do
    total=total+v*(v-1)//2
end
print(total)

Score : 300 points

Problem Statement

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

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

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

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

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

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

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

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

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

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

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

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

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


function tabtostr(t, n)
  local s=""
  for i=1, n do
    s=string.format("%s%s", s, t[i])
  end
  return s
end

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

for i=1, n do
  si={}
  for j=1, 11 do
    table.insert(si, io.read(1))
  end
  table.sort(si, function(a, b) return a:upper() < b:upper() end)
  table.insert(s, tabtostr(si, 11))
end

ans=0
for i=1, n do
  for j=i, n do
    if s[i]==s[j+1] then
      ans=ans+1
    end
  end
end

print(ans)


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

local function nC2(n)
    if n < 2 then
        return 0
    end
    return n * (n-1) // 2
end
---
local N, _ = io.read("n", "l")
local sorted_dic = {}
for i=1,N do
    local s = io.read("l")
    local s_tbl = str2tbl(s)
    table.sort(s_tbl)
    local s_sorted = table.concat(s_tbl, "")
    --print(s_sorted)
    sorted_dic[s_sorted] = (sorted_dic[s_sorted] or 0) + 1
end
local ans = 0
for k,v in pairs(sorted_dic) do
    ans = ans + nC2(v)
end
print(ans)


local n = io.read("*n", "*l")
local map = {}
for i = 1, n do
  local str = io.read()
  local t = {}
  for i = 1, 10 do
    table.insert(t, str:sub(i, i))
    table.sort(t)
  end
  local sorted = table.concat(t)
  if not map[sorted] then map[sorted] = 1
  else map[sorted] = map[sorted] + 1
  end
end
local ret = 0
for k, v in pairs(map) do
  ret = ret + (v * (v - 1)) // 2
end
print(ret)


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

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

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

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

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

local tree = SegTree.new(treeary, function(x, y)
  if x[2] == y[2] then
    if x[1] < y[1] then
      return y
    else
      return x
    end
  elseif x[2] < y[2] then
    return y
  else
    return x
  end
end, {0, 0})

local ret = 0
for i = 1, m do
  local ub = upper_bound(alist, i)
  if 1 < ub then
    local r = tree:getRange(1, ub - 1)
    local idx, val = r[1], r[2]
    tree:setValue(idx, {idx, 0})
    ret = ret + val
  end
end
print(ret)

Score : 400 points

Problem Statement

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

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

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

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

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

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

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

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

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

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

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0