Score : 100 points

Problem Statement

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

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

The taxi will cost us a total of B yen.

How much is our minimum total travel expense?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq A \leq 50

1 \leq B \leq 50

Input

Input is given from Standard Input in the following format:

N A B

Output

Print an integer representing the minimum total travel expense.

Sample Input 1

4 2 9

Sample Output 1

8

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

Sample Input 2

4 2 7

Sample Output 2

7

Sample Input 3

4 2 8

Sample Output 3

8


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

Submitted source-code file size, in bytes.

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

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


local N, D = io.read("n","n")
local X = {}
for i=1,N do
    local p = {}
    for j=1,D do
        table.insert(p, io.read("n"))
    end
    table.insert(X, p)
end
local function d(i,j)
    local sq = 0
    for k=1,D do
        sq = sq + (X[i][k] - X[j][k])^2
    end
    return math.sqrt(sq)
end
local function is_int(x)
    return x - math.floor(x) == 0
end
local ans = 0
for i=1,N-1 do
    for j=i+1, N do
        if is_int(d(i,j)) then
            ans = ans + 1
        end
    end
end
print(ans)

Score : 200 points

Problem Statement

There are N points in a D-dimensional space.

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10

1 \leq D \leq 10

-20 \leq X_{ij} \leq 20

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3 2
1 2
5 5
-2 8

Sample Output 1

1

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

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

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

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

Sample Input 2

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

Sample Output 2

2

Sample Input 3

5 1
1
2
3
4
5

Sample Output 3

10


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local n = io.read("*n")
local a = {}
local sum = 0
for i = 1, n do
  a[i] = 2 * io.read("*n")
  sum = sum + a[i]
end
sum = sum / 2
-- get t1
local t = {}
t[1] = sum
for i = 2, n, 2 do
  t[1] = t[1] - a[i]
end
-- print(t[1])
for i = 2, n do
  t[i] = a[i - 1] - t[i - 1]
end
io.write(t[1])
for i = 2, n do
  io.write(" " .. t[i])
end
io.write("\n")

Score : 400 points

Problem Statement

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

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

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

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

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

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

Constraints

All values in input are integers.

3 \leq N \leq 10^5-1

N is an odd number.

0 \leq A_i \leq 10^9

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

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

3
2 2 4

Sample Output 1

4 0 4

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

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

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

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

Sample Input 2

5
3 8 7 5 5

Sample Output 2

2 4 12 2 8

Sample Input 3

3
1000000000 1000000000 0

Sample Output 3

0 2000000000 0


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

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

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

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

Score : 600 points

Problem Statement

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

Answer the following Q queries:

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

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

1 \leq a_i, b_i \leq N

1 \leq c_i \leq N-1

1 \leq d_i \leq 10^4

1 \leq x_j \leq N-1

1 \leq y_j \leq 10^4

1 \leq u_j < v_j \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

130
200
60

The graph in this input is as follows:

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

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

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

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


local s = io.read("l")
local a, b, c, d = string.byte(s, 1, 4)
if ((a == b) and (c == d)) or
   ((a == c) and (b == d)) or
   ((a == d) and (b == c)) then
   if (a == b) and (a == c) then
       print("No")
   else
       print("Yes")
   end
else
   print("No")
end

Score : 100 points

Problem Statement

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

Constraints

The length of S is 4.

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

ASSA

Sample Output 1

Yes

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

Sample Input 2

STOP

Sample Output 2

No

Sample Input 3

FFEE

Sample Output 3

Yes

Sample Input 4

FREE

Sample Output 4

No


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

Score : 200 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

3 \leq n \leq 20

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

Input

Input is given from Standard Input in the following format:

n
p_1 p_2 ... p_n

Output

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

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

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

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5


local n, m = io.read("*n", "*n")
local edge = {}
for i = 1, n do edge[i] = {} end
for i = 1, m do
  local u, v = io.read("*n", "*n")
  table.insert(edge[u], v)
end
local s, t = io.read("*n", "*n")

local len = {}
for i = 1, 3 * n do
  len[i] = -1
end
local start_idx = (s - 1) * 3 + 1
len[start_idx] = 0

local taskstate = {}
for i = 1, 3 * n do taskstate[i] = false end
local tasks = {}
local tasknum = 0
local done = 0
local tasklim = 3 * n

local function addtask(idx)
  if not taskstate[idx] then
    taskstate[idx] = true
    tasknum = tasknum + 1
    local taskidx = tasknum % tasklim
    if taskidx == 0 then taskidx = tasklim end
    tasks[taskidx] = idx
  end
end

local function walk(src, dst)
  if len[dst] < 0 or len[src] + 1 < len[dst] then
    len[dst] = len[src] + 1
    addtask(dst)
  end
end

addtask(start_idx)
local mfl = math.floor

while done < tasknum do
  done = done + 1
  local taskidx = done % tasklim
  if taskidx == 0 then taskidx = tasklim end
  local srcidx = tasks[taskidx]
  taskstate[srcidx] = false
  local pos = 1 + mfl((srcidx - 1) / 3)
  local rem = srcidx - (pos - 1) * 3
  local dstrem = rem + 1
  if dstrem == 4 then dstrem = 1 end
  for i = 1, #edge[pos] do
    local dstpos = edge[pos][i]
    local dstidx = (dstpos - 1) * 3 + dstrem
    walk(srcidx, dstidx)
  end
end
local goal_idx = (t - 1) * 3 + 1
local ret = len[goal_idx]
if 0 < ret then ret = math.floor(ret / 3) end
print(ret)

Score : 500 points

Problem Statement

Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G.
G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.

First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.

Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq \min(10^5, N (N-1))

1 \leq u_i, v_i \leq N(1 \leq i \leq M)

u_i \neq v_i (1 \leq i \leq M)

If i \neq j, (u_i, v_i) \neq (u_j, v_j).

1 \leq S, T \leq N

S \neq T

Input

Input is given from Standard Input in the following format:

N M
u_1 v_1
:
u_M v_M
S T

Output

If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1.
If he can, print the minimum number of ken-ken-pa needed to reach vertex T.

Sample Input 1

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

Sample Output 1

2

Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.

Sample Input 2

3 3
1 2
2 3
3 1
1 2

Sample Output 2

-1

Any number of ken-ken-pa will bring Ken back to Vertex 1, so he cannot reach Vertex 2, though he can pass through it in the middle of a ken-ken-pa.

Sample Input 3

2 0
1 2

Sample Output 3

-1

Vertex S and Vertex T may be disconnected.

Sample Input 4

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

Sample Output 4

2


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

local function gcdmany(tbl)
    local ans = tbl[1]
    for i=2,#tbl do
        ans = gcd(ans, tbl[i])
    end
    return ans
end

local function lcm(a, b)
    return a // gcd(a, b) * b
end

local function lcmmany(tbl)
    local ans = tbl[1]
    for i=2, #tbl do
        ans = lcm(ans, tbl[i])
    end
    return ans
end

---
local A, B, C, D = io.read("n", "n", "n", "n")
local function candiv(x)
    return (B // x) - ((A-1) // x)
end
local total = B - A + 1
local c_div = candiv(C)
local d_div = candiv(D)
local cd_lcm = lcm(C, D)
local cd_div = candiv(cd_lcm)
local ans = total - c_div - d_div + cd_div
print(ans)

Score : 300 points

Problem Statement

You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Constraints

1\leq A\leq B\leq 10^{18}

1\leq C,D\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Sample Input 1

4 9 2 3

Sample Output 1

2

5 and 7 satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368


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

local total=0
for i=1,n do
    total=total+works[i][1]
    if total>works[i][2] then
        print("No")
        return
    end
end
print("Yes")

Score: 400 points

Problem Statement

Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.

Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.

It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B_i, and he must complete the job before or at this time.

Kizahashi cannot work on two or more jobs simultaneously, but when he completes a job, he can start working on another immediately.

Can Kizahashi complete all the jobs in time? If he can, print Yes; if he cannot, print No.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
.
.
.
A_N B_N

Output

If Kizahashi can complete all the jobs in time, print Yes; if he cannot, print No.

Sample Input 1

5
2 4
1 9
1 8
4 9
3 12

Sample Output 1

Yes

He can complete all the jobs in time by, for example, doing them in the following order:

Do Job 2 from time 0 to 1.

Do Job 1 from time 1 to 3.

Do Job 4 from time 3 to 7.

Do Job 3 from time 7 to 8.

Do Job 5 from time 8 to 11.

Note that it is fine to complete Job 3 exactly at the deadline, time 8.

Sample Input 2

3
334 1000
334 1000
334 1000

Sample Output 2

No

He cannot complete all the jobs in time, no matter what order he does them in.

Sample Input 3

30
384 8895
1725 9791
170 1024
4 11105
2 6
578 1815
702 3352
143 5141
1420 6980
24 1602
849 999
76 7586
85 5570
444 4991
719 11090
470 10708
1137 4547
455 9003
110 9901
15 8578
368 3692
104 1286
3 4
366 12143
7 6649
610 2374
152 7324
4 7042
292 11386
334 5720

Sample Output 3

Yes


--締切の早いやつからやるべき？
local n=io.read("*n")
local works={}
for i=1,n do
    works[i]={io.read("*n","*n")}
end
table.sort(works,function(a,b)
    return a[2]<b[2]
end)

local total=0
for i=1,n do
    total=total+works[i][1]
    if total>works[i][2] then
        print("No")
        return
    end
end
print("Yes")


local n = io.read("*n")
local a, b = {}, {}
local idx = {}
for i = 1, n do
  a[i], b[i] = io.read("*n", "*n")
  idx[i] = i
end
table.sort(idx, function(x, y) return b[x] < b[y] end)
local cur = 0
local valid = true
for i = 1, n do
  local ai, bi = a[idx[i]], b[idx[i]]
  if bi < cur + ai then
    valid = false break
  end
  cur = cur + ai
end
print(valid and "Yes" or "No")


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

local parent = {}
for i = 1, 2 * n do parent[i] = i end

local function uf_findroot(idx)
  local idx_update = idx
  while parent[idx] ~= idx do
    idx = parent[idx]
  end
  while parent[idx_update] ~= idx do
    parent[idx_update], idx_update = idx, parent[idx_update]
  end
  return idx
end

local x, y = {}, {}
local xinvmap, yinvmap = {}, {}
local xary, yary = {}, {}
for i = 1, n do
  x[i], y[i] = io.read("*n", "*n")
  if not xinvmap[x[i]] then
    table.insert(xary, x[i])
    xinvmap[x[i]] = #xary
  end
  if not yinvmap[y[i]] then
    table.insert(yary, y[i])
    yinvmap[y[i]] = n + #yary
  end
end

for i = 1, n do
  local xi, yi = x[i], y[i]
  local idx1, idx2 = xinvmap[xi], yinvmap[yi]
  local p1, p2 = uf_findroot(idx1), uf_findroot(idx2)
  parent[p2], parent[idx2] = p1, p1
end
local groups = {}
for i = 1, 2 * n do
  local p = uf_findroot(i)
  if not groups[p] then
    groups[p] = {}
    groups[p].xcnt = 0
    groups[p].ycnt = 0
    groups[p].pointcnt = 0
  end
  if i <= n then
    groups[p].xcnt = groups[p].xcnt + 1
  else
    groups[p].ycnt = groups[p].ycnt + 1
  end
end
for i = 1, n do
  local xi, yi = x[i], y[i]
  local p = uf_findroot(xinvmap[xi])
  groups[p].pointcnt = groups[p].pointcnt + 1
end
local ret = 0
for k, v in pairs(groups) do
  if 1 < v.xcnt and 1 < v.ycnt then
    ret = ret + v.xcnt * v.ycnt - v.pointcnt
  end
end
print(ret)

Score : 600 points

Problem Statement

There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i).

We will repeat the following operation as long as possible:

Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at the remaining position.

We can prove that we can only do this operation a finite number of times. Find the maximum number of times we can do the operation.

Constraints

1 \leq N \leq 10^5

1 \leq x_i, y_i \leq 10^5

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the maximum number of times we can do the operation.

Sample Input 1

3
1 1
5 1
5 5

Sample Output 1

1

By choosing a = 1, b = 1, c = 5, d = 5, we can add a dot at (1, 5). We cannot do the operation any more, so the maximum number of operations is 1.

Sample Input 2

2
10 10
20 20

Sample Output 2

0

There are only two dots, so we cannot do the operation at all.

Sample Input 3

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

Sample Output 3

16

We can do the operation for all choices of the form a = 1, b = 1, c = i, d = j (2 \leq i,j \leq 5), and no more. Thus, the maximum number of operations is 16.


local X, A = io.read("n", "n")
print(X < A and 0 or 10)

Score : 100 points

Problem Statement

X and A are integers between 0 and 9 (inclusive).

If X is less than A, print 0; if X is not less than A, print 10.

Constraints

0 \leq X, A \leq 9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X A

Output

If X is less than A, print 0; if X is not less than A, print 10.

Sample Input 1

3 5

Sample Output 1

0

3 is less than 5, so we should print 0.

Sample Input 2

7 5

Sample Output 2

10

7 is not less than 5, so we should print 10.

Sample Input 3

6 6

Sample Output 3

10

6 is not less than 6, so we should print 10.


local x, a = io.stdin:read();
if x < a then print(0) else print(10) end

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.


local N, X = io.read("n", "n")
local D = 0
local count = 1
for k=1, N do
    local L = io.read("n")
    D = D + L
    if D <= X then
        count = count + 1
    end
end
print(count)


local w,h,x,y=io.read("*n","*n","*n","*n")
local max=string.format("%.10f",w*h/2)
print(max,w==2*x and h==2*y and 1 or 0)

Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


local function same(a, b)
    return math.abs(a-b) < 10^-9
end
local W, H, x, y = io.read("n", "n", "n", "n")
local cw, ch = W/2, H/2
local space = W*H/2
local mult = 0
if same(x, cw) and same(y, ch) then
    mult = 1
end
print(space, mult)


local W, H, x, y = io.read("*n","*n","*n", "*n")
local rect = W * H / 2
local flg = 0

if 2*x == W and 2*y == H then
  flg = 1
end

print(string.format("%.10f", rect))
print(" " .. flg .. "\n")


local n=io.read("n")
local x,y={},{}
for i=1,n do
    x[i],y[i]=io.read("n","n")
end

local map={}
for i=1,n do
    for j=1,n do
        if i~=j then
            local p=tostring(x[i]-x[j])
            local q=tostring(y[i]-y[j])
            local s=p.." "..q
            map[s]=(map[s] or 0)+1
        end
    end
end

local mincost=n
for k,v in pairs(map) do
    mincost=math.min(mincost,n-v)
end
print(mincost)

Score : 300 points

Problem Statement

There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).

We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:

Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates of this ball. If we collected a ball at coordinates (a - p, b - q) in the previous operation, the cost of this operation is 0. Otherwise, including when this is the first time to do this operation, the cost of this operation is 1.

Find the minimum total cost required to collect all the balls when we optimally choose p and q.

Constraints

1 \leq N \leq 50

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

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the minimum total cost required to collect all the balls.

Sample Input 1

2
1 1
2 2

Sample Output 1

1

If we choose p = 1, q = 1, we can collect all the balls at a cost of 1 by collecting them in the order (1, 1), (2, 2).

Sample Input 2

3
1 4
4 6
7 8

Sample Output 2

1

If we choose p = -3, q = -2, we can collect all the balls at a cost of 1 by collecting them in the order (7, 8), (4, 6), (1, 4).

Sample Input 3

4
1 1
1 2
2 1
2 2

Sample Output 3

2


local n = io.read("*n")
local p, m = {}, {}
for i = 1, n do
  local a = io.read("*n")
  if 0 <= a then
    table.insert(p, a)
  else
    table.insert(m, a)
  end
end
table.sort(p)
table.sort(m, function(a, b) return a > b end)
local v = 0
local r1, r2 = {}, {}
if #m == 0 then
  v = p[1]
  for i = 3, #p do
    table.insert(r1, v)
    table.insert(r2, p[i])
    v = v - p[i]
  end
  table.insert(r1, p[2])
  table.insert(r2, v)
  v = p[2] - v
elseif #p == 0 then
  v = m[1]
  for i = 2, #m do
    table.insert(r1, v)
    table.insert(r2, m[i])
    v = v - m[i]
  end
else
  v = m[1]
  for i = 2, #p do
    table.insert(r1, v)
    table.insert(r2, p[i])
    v = v - p[i]
  end
  table.insert(r1, p[1])
  table.insert(r2, v)
  v = p[1] - v
  for i = 2, #m do
    table.insert(r1, v)
    table.insert(r2, m[i])
    v = v - m[i]
  end
end
print(v)
for i = 1, n - 1 do
  print(r1[i] .. " " ..r2[i])
end

Score : 500 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on a blackboard.

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0


local n = io.read("*n")
local p, m = {}, {}
for i = 1, n do
  local a = io.read("*n")
  if 0 <= a then
    table.insert(p, a)
  else
    table.insert(m, a)
  end
end
local v = 0
local r1, r2 = {}, {}
if #m == 0 then
  v = p[1]
  for i = 3, #p do
    table.insert(r1, v)
    table.insert(r2, p[i])
    v = v - p[i]
  end
  table.insert(r1, p[2])
  table.insert(r2, v)
  v = p[2] - v
elseif #p == 0 then
  v = m[1]
  for i = 2, #m do
    table.insert(r1, v)
    table.insert(r2, m[i])
    v = v - m[i]
  end
else
  v = m[1]
  for i = 2, #p do
    table.insert(r1, v)
    table.insert(r2, p[i])
    v = v - p[i]
  end
  table.insert(r1, p[1])
  table.insert(r2, v)
  v = p[1] - v
  for i = 2, #m do
    table.insert(r1, v)
    table.insert(r2, m[i])
    v = v - m[i]
  end
end
print(v)
for i = 1, n - 1 do
  print(r1[i] .. " " ..r2[i])
end


local mab = math.abs
local n = io.read("*n")
local a = {}
local sum = 0
local abssum = 0
for i = 1, n do
  a[i] = io.read("*n")
  sum = sum + a[i]
  abssum = abssum + mab(a[i])
end
table.sort(a)
local allplus = 0 <= a[1]
local allminus = a[n] < 0

if n == 2 then
  if a[1] < a[2] then
    print(a[2] - a[1])
    print(a[2] .. " " .. a[1])
  else
    print(a[1] - a[2])
    print(a[1] .. " " .. a[2])
  end
else
  if allplus then
    print(sum - a[1] * 2)
    local cur = a[1]
    for i = 2, n - 1 do
      print(cur .. " " .. a[i])
      cur = cur - a[i]
    end
    print(a[n] .. " " .. cur)
  elseif allminus then
    print(a[n] * 2 - sum)
    local cur = a[n]
    for i = 1, n - 1 do
      print(cur .. " " .. a[i])
      cur = cur - a[i]
    end
  else
    print(abssum)
    local minlast = 1
    for i = 1, n do
      if a[i] < 0 then
        minlast = i
      else
        break
      end
    end
    local cur = a[minlast]
    for i = minlast + 1, n - 1 do
      print(cur .. " " .. a[i])
      cur = cur - a[i]
    end
    print(a[n] .. " " .. cur)
    cur = a[n] - cur
    for i = 1, minlast - 1 do
      print(cur .. " " .. a[i])
      cur = cur - a[i]
    end
  end
end


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local p = io.read("*n")
local q, r = io.read("*n", "*n")
local s = p + q + r
s = s - mma(p, mma(q, r))
print(s)

Score : 100 points

Problem Statement

There are three airports A, B and C, and flights between each pair of airports in both directions.

A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.

Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

The sum of the flight times in the route A \rightarrow B \rightarrow C: 1 + 3 = 4 hours

The sum of the flight times in the route A \rightarrow C \rightarrow C: 4 + 3 = 7 hours

The sum of the flight times in the route B \rightarrow A \rightarrow C: 1 + 4 = 5 hours

The sum of the flight times in the route B \rightarrow C \rightarrow A: 3 + 4 = 7 hours

The sum of the flight times in the route C \rightarrow A \rightarrow B: 4 + 1 = 5 hours

The sum of the flight times in the route C \rightarrow B \rightarrow A: 3 + 1 = 4 hours

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5


n = io.read("*n")
w = {}
sum = 0
for i = 1, n do
  w[i] = io.read("*n")
  sum = sum + w[i]
end
l = 0
ret = sum
for i = 1, n - 1 do
  l = l + w[i]
  ret = math.min(ret, math.abs(sum - l - l))
end
print(ret)

Score : 200 points

Problem Statement

We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.

We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group.

Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2.

Constraints

2 \leq N \leq 100

1 \leq W_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
W_1 W_2 ... W_{N-1} W_N

Output

Print the minimum possible absolute difference of S_1 and S_2.

Sample Input 1

3
1 2 3

Sample Output 1

0

If T = 2, S_1 = 1 + 2 = 3 and S_2 = 3, with the absolute difference of 0.

Sample Input 2

4
1 3 1 1

Sample Output 2

2

If T = 2, S_1 = 1 + 3 = 4 and S_2 = 1 + 1 = 2, with the absolute difference of 2. We cannot have a smaller absolute difference.

Sample Input 3

8
27 23 76 2 3 5 62 52

Sample Output 3

2


local N = io.read("n")
local W = {}

for i=1, N do
    local w = io.read("n")
    W[i] = w
end

local ans = 100 * 100
for T=1,N do
    local sum_left = 0
    local sum_right = 0
    for i=1,T do
        sum_left = sum_left + W[i]
    end
    for i=T+1,N do
        sum_right = sum_right + W[i]
    end
    ans = math.min(ans, math.abs(sum_left - sum_right))
end
print(ans)


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local mab = math.abs
local n = io.read("*n")
local w = {}
for i = 1, n do w[i] = io.read("*n") end
local sum = {}
sum[1] = w[1]
for i = 2, n do
  sum[i] = sum[i - 1] + w[i]
end
local dif = mab((sum[n] - sum[1]) - sum[1])
for i = 2, n - 1 do
  local adif = mab((sum[n] - sum[i]) - sum[i])
  dif = mmi(dif, adif)
end
print(dif)


local mod = 1000000007
local function badd(x, y) return (x + y) % mod end
local n, m = io.read("*n", "*n")
local f, dp = {}, {}
for i = 1, n + 2 do
  f[i] = true
  dp[i] = 0
end
for i = 1, m do
  local a = io.read("*n")
  f[a + 1] = false
end
dp[1] = 1
for i = 1, n do
  if f[i] then
    dp[i + 1] = badd(dp[i + 1], dp[i])
    dp[i + 2] = badd(dp[i + 2], dp[i])
  end
end
print(dp[n + 1])

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.


local h, w = io.read("*n", "*n", "*l")
local t = {}
local s_sharp = string.byte("#")
for i = 1, h do
  local s = io.read()
  for j = 1, w do
    local idx = (i - 1) * w + j
    t[idx] = s:byte(j) ~= s_sharp
  end
end
local score = {}
for i = 1, h * w do score[i] = 0 end
local len = 0
local function func(idx)
  score[idx] = score[idx] + len
  if t[idx] then len = len + 1
  else len = 0
  end
end
for i = 1, h do
  len = 0
  for j = 1, w do
    func((i - 1) * w + j)
  end
end
for i = 1, h do
  len = 0
  for j = w, 1, -1 do
    func((i - 1) * w + j)
  end
end
for j = 1, w do
  len = 0
  for i = 1, h do
    func((i - 1) * w + j)
  end
end
for j = 1, w do
  len = 0
  for i = h, 1, -1 do
    func((i - 1) * w + j)
  end
end
local ret = 0
local mma = math.max
for i = 1, h * w do
  if t[i] then
    ret = mma(ret, score[i])
  end
end
print(ret + 1)

Score : 400 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given H strings S_i (1 \leq i \leq H), each of length W. If the j-th character (1 \leq j \leq W) of S_i is #, there is an obstacle on the square at the i-th row from the top and the j-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

1 \leq H \leq 2,000

1 \leq W \leq 2,000

S_i is a string of length W consisting of # and ..

. occurs at least once in one of the strings S_i (1 \leq i \leq H).

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13


local n = io.read("*n")
local a = io.read("*n")
local b = io.read("*n")
local c = io.read("*n")
local d = io.read("*n")
io.read("*l")
local s = io.read("*l")
local empty = string.byte(".", 1)
local rock = string.byte("#", 1)
if a > b then
	a, b = b, a
	c, d = d, c
end
local threeempty = false
for i = 1, math.max(c, d) do
	if a < i and i < c and string.byte(s, i) == rock and string.byte(s, i + 1) == rock then
		print("No")
		return
	end
	if b < i and i < d and string.byte(s, i) == rock and string.byte(s, i + 1) == rock then
		print("No")
		return
	end
	if b <= i and i <= d and i + 2 <= n and string.byte(s, i) == empty and string.byte(s, i + 1) == empty and string.byte(s, i + 2) == empty then
		threeempty = true
	end
end

if d < c then
	if not threeempty then
		print('No')
		return
	end
end
print("Yes")

Score : 400 points

Problem Statement

There are N squares arranged in a row, numbered 1, 2, ..., N from left to right.
You are given a string S of length N consisting of . and #. If the i-th character of S is #, Square i contains a rock; if the i-th character of S is ., Square i is empty.

In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

S is a string of length N consisting of . and #.

1 \leq A, B, C, D \leq N

Square A, B, C and D do not contain a rock.

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

Yes


local n = io.read("*n")
local a = io.read("*n")
local b = io.read("*n")
local c = io.read("*n")
local d = io.read("*n")
io.read("*l")
local s = io.read("*l")
local empty = string.byte(".", 1)
local rock = string.byte("#", 1)
if a > b then
	a, b = b, a
	c, d = d, c
end
local threeempty = false
for i = 1, math.max(c, d) do
	if a < i and i < c and string.byte(s, i) == rock and string.byte(s, i + 1) == rock then
		print("No")
		return
	end
	if b < i and i < d and string.byte(s, i) == rock and string.byte(s, i + 1) == rock then
		print("No")
	end
	if b <= i and i <= d and i + 2 <= n and string.byte(s, i) == empty and string.byte(s, i + 1) == empty and string.byte(s, i + 2) == empty then
		threeempty = true
	end
end

if d < c then
	if not threeempty then
		print('No')
		return
	end
end
print("Yes")


local n,a,b,c,d=io.read("*n","*n","*n","*n","*n","*l")
local s=io.read()

if c<d then
    local flag=true
    for i=a,c-1 do
        if s:sub(i,i+1)=="##" then
            flag=false
        end
    end
    for i=b,d-1 do
        if s:sub(i,i+1)=="##" then
            flag=false
        end
    end
    print(flag and "Yes" or "No")
elseif c>d then
    local flag=true
    for i=a,c-1 do
        if s:sub(i,i+1)=="##" then
            flag=false
        end
    end
    for i=b,d-1 do
        if s:sub(i,i+1)=="##" then
            flag=false
        end
    end
    if flag then
        flag=false
        for i=b-1,d-1 do
            if s:sub(i,i+2)=="..." then
                flag=true
            end
        end
        print(flag and "Yes" or "No")
    end
end


local n,a,b,c,d=io.read("*n","*n","*n","*n","*n","*l")
local s=io.read()

if #s:sub(a,c):match("#+")>1 or #s:sub(b,d):match("#+")>1 then
    print("No")
else
    if c>d then
        for i=b-1,d-1 do
            if s:sub(i,i+2)=="..." then
                print("Yes")
                return
            end
        end
        print("No")
    else
        print("Yes")
    end
end


local n, a, b, c, d = io.read("*n", "*n", "*n", "*n", "*n", "*l")
local s = io.read()

local function check1(l, r)
  for i = l, r - 1 do
    if s:sub(i, i) == "#" and s:sub(i + 1, i + 1) == "#" then
      return false
    end
  end
  return true
end

local function check2(l, r)
  for i = l, r - 2 do
    if s:sub(i, i) == "." and s:sub(i + 1, i + 1) == "." and s:sub(i + 2, i + 2) == "." then
      return true
    end
  end
  return false
end

if c < d then
  local r = check1(a, c) and check1(b, d)
  print(r and "Yes" or "No")
else
  local r = check1(a, c)
  if not r then print("No")
  else
    r = check2(b - 1, d + 1)
    print(r and "Yes" or "No")
  end
end


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local mod = 1000000007
local function bmul(x, y)
  local x1, y1 = x % 10000, y % 10000
  local x2, y2 = mfl(x / 10000) % 10000, mfl(y / 10000) % 10000
  local x3, y3 = mfl(x / 100000000), mfl(y / 100000000)
  local ret = (x1 * y1 + (x1 * y2 + x2 * y1) * 10000) % mod
  ret = (ret + (x1 * y3 + x2 * y2 + x3 * y1) * 10000 % mod * 10000 % mod) % mod
  ret = (ret + (x2 * y3 + x3 * y2) * 10000 % mod * 10000 % mod * 10000) % mod
  ret = (ret + x3 * y3 * 930000007) % mod
  return ret
end

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

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

local cmb = 1
local n, a, b, c = io.read("*n", "*n", "*n", "*n")
local e = 0
local ta = bmul(a, modinv(a + b))
local tb = bmul(b, modinv(a + b))
for x = n, 2 * n - 1 do
  if x == n then cmb = 1
  else
    cmb = bmul(cmb, x - 1)
    cmb = bmul(cmb, modinv(x - 2 - (n - 1) + 1))
  end
  -- local cmb = getComb(x - 1, n - 1)
  local p1 = cmb
  local q = modpow(ta, n)
  local r = modpow(tb, x - n)
  p1 = bmul(p1, bmul(q, r))
  p1 = bmul(p1, x)

  local p2 = cmb
  q = modpow(tb, n)
  r = modpow(ta, x - n)
  p2 = bmul(p2, bmul(q, r))
  p2 = bmul(p2, x)

  local p = p1 + p2
  -- print(p1, p2)
  p = bmul(p, modinv(a + b))
  p = bmul(p, 100)
  e = (e + p) % mod
end
print(e)

Score : 500 points

Problem Statement

Takahashi and Aoki will play a game. They will repeatedly play it until one of them have N wins in total.

When they play the game once, Takahashi wins with probability A %, Aoki wins with probability B %, and the game ends in a draw (that is, nobody wins) with probability C %.
Find the expected number of games that will be played, and print it as follows.

We can represent the expected value as P/Q with coprime integers P and Q.
Print the integer R between 0 and 10^9+6 (inclusive) such that R \times Q \equiv P\pmod {10^9+7}.
(Such an integer R always uniquely exists under the constraints of this problem.)

Constraints

1 \leq N \leq 100000

0 \leq A,B,C \leq 100

1 \leq A+B

A+B+C=100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C

Output

Print the expected number of games that will be played, in the manner specified in the statement.

Sample Input 1

1 25 25 50

Sample Output 1

2

Since N=1, they will repeat the game until one of them wins.
The expected number of games played is 2.

Sample Input 2

4 50 50 0

Sample Output 2

312500008

C may be 0.

Sample Input 3

1 100 0 0

Sample Output 3

1

B may also be 0.

Sample Input 4

100000 31 41 28

Sample Output 4

104136146


local n = io.read("*n")
local edge = {}
local edgecnt = {}
local cost = {}
for i = 1, n do
  edge[i] = {}
  edgecnt[i] = 0
  cost[i] = 0
end
for i = 1, n - 1 do
  local a, b = io.read("*n", "*n")
  edgecnt[a] = edgecnt[a] + 1
  edgecnt[b] = edgecnt[b] + 1
  edge[a][b], edge[b][a] = true, true
end
local c = {}
for i = 1, n do
  c[i] = io.read("*n")
end
table.sort(c)
do
  local csum = 0
  for i = 1, n - 1 do
    csum = csum + c[i]
  end
  print(csum)
end
local tasks = {}
for i = 1, n do
  if edgecnt[i] == 1 then
    table.insert(tasks, i)
  end
end
for i = 1, n do
  local src = tasks[i]
  cost[src] = c[i]
  for dst, _u in pairs(edge[src]) do
    if 1 < edgecnt[dst] then
      edgecnt[dst] = edgecnt[dst] - 1
      if edgecnt[dst] == 1 then
        table.insert(tasks, dst)
      end
    end
  end
end
print(table.concat(cost, " "))

Score : 500 points

Problem Statement

You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N.
The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.

We will write a positive integer on each vertex in T and calculate our score as follows:

On each edge, write the smaller of the integers written on the two endpoints.

Let our score be the sum of the integers written on all the edges.

Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.

Constraints

1 \leq N \leq 10000

1 \leq a_i,b_i \leq N

1 \leq c_i \leq 10^5

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N

Output

Use the following format:

M
d_1 \ldots d_N

where M is the maximum possible score, and d_i is the integer to write on Vertex i.
d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N.
If there are multiple ways to achieve the maximum score, any of them will be accepted.

Sample Input 1

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

Sample Output 1

10
1 2 3 4 5

If we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written on the four edges will be 1,2,3,4, for the score of 10. This is the maximum possible score.

Sample Input 2

5
1 2
1 3
1 4
1 5
3141 59 26 53 59

Sample Output 2

197
59 26 3141 59 53

c_1,c_2,\ldots,c_N may not be pairwise distinct.


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local n = io.read("*n")
local at, bt = {}, {}
local c = {}
local ref = {}
for i = 1, n do
  ref[i] = {}
  ref[i].dst = {}
  ref[i].dstnum = 0
  ref[i].c = 0
  ref[i].reserved = false
end
for i = 1, n - 1 do
  local a, b = io.read("*n", "*n")
  at[i], bt[i] = a, b
  table.insert(ref[a].dst, b)
  table.insert(ref[b].dst, a)
  ref[a].dstnum, ref[b].dstnum = ref[a].dstnum + 1, ref[b].dstnum + 1
end
for i = 1, n do
  c[i] = io.read("*n")
end
table.sort(c)
local tasks = {}
local tasknum, done = 0, 0
local function addtask(idx)
  ref[idx].reserved = true
  table.insert(tasks, idx)
  tasknum = tasknum + 1
end
for i = 1, n do
  if #(ref[i].dst) == 1 then
    addtask(i)
  end
end
while done < tasknum do
  done = done + 1
  local idx = tasks[done]
  ref[idx].c = c[done]
  for i = 1, #(ref[idx].dst) do
    local dstidx = ref[idx].dst[i]
    if not ref[dstidx].reserved then
      ref[dstidx].dstnum = ref[dstidx].dstnum - 1
      if ref[dstidx].dstnum == 1 then
        addtask(dstidx)
      end
    end
  end
end

local sum = 0
for i = 1, n - 1 do
  sum = sum + mmi(ref[at[i]].c, ref[bt[i]].c)
end
print(sum)
io.write(ref[1].c)
for i = 2, n do
  io.write(" " .. ref[i].c)
end
io.write("\n")


local mce, mfl, msq, mmi, mma = math.ceil, math.floor, math.sqrt, math.min, math.max
local n = io.read("*n")
local at, bt, c = {}, {}
local c = {}
local ref = {}
for i = 1, n do
  ref[i] = {}
  ref[i].idx = i
  ref[i].v = 0
  ref[i].c = 0
end
for i = 1, n - 1 do
  local a, b = io.read("*n", "*n")
  at[i], bt[i] = a, b
  ref[a].v, ref[b].v = ref[a].v + 1, ref[b].v + 1
end
for i = 1, n do
  c[i] = io.read("*n")
end
table.sort(ref, function(x, y) return x.v < y.v end)
table.sort(c)
for i = 1, n do
  ref[i].c = c[i]
end
table.sort(ref, function(x, y) return x.idx < y.idx end)
local sum = 0
for i = 1, n - 1 do
  sum = sum + mmi(ref[at[i]].c, ref[bt[i]].c)
end
print(sum)
io.write(ref[1].c)
for i = 2, n do
  io.write(" " .. ref[i].c)
end
io.write("\n")


a, p = io.read("*n", "*n")
print(math.floor((a * 3 + p) / 2))

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58


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
local str2tbl = function(s) local t={} local u=string.sub for i=1,#s do t[i] = u(s, i, i) end return t end
string.split = function(s) local t={} for w in string.gmatch(s, "[^%s]+") do table.insert(t, w) end return (table.unpack or unpack)(t) end
--
local N = read.nl()
local cities = {}
for i=1,N do
    local s, p = read.l():split()
    p = tonumber(p)
    cities[s] = cities[s] or {}
    table.insert(cities[s], {i, p})
end

local cities2 = {}
for city in pairs(cities) do
    table.insert(cities2, city)
end
table.sort(cities2, function (x,y) return x<y end)

for _,cname in ipairs(cities2) do
    local city = cities[cname]
    table.sort(city, function (x,y) return x[2]>y[2] end)
    for _, r in ipairs(city) do
        print(r[1])
    end
end

Score : 200 points

Problem Statement

You have decided to write a book introducing good restaurants.
There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i.
No two restaurants have the same score.

You want to introduce the restaurants in the following order:

The restaurants are arranged in lexicographical order of the names of their cities.

If there are multiple restaurants in the same city, they are arranged in descending order of score.

Print the identification numbers of the restaurants in the order they are introduced in the book.

Constraints

1 ≤ N ≤ 100

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

0 ≤ P_i ≤ 100

P_i is an integer.

P_i ≠ P_j (1 ≤ i < j ≤ N)

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

Print N lines. The i-th line (1 ≤ i ≤ N) should contain the identification number of the restaurant that is introduced i-th in the book.

Sample Input 1

6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40

Sample Output 1

3
4
6
1
5
2

The lexicographical order of the names of the three cities is kazan < khabarovsk < moscow. For each of these cities, the restaurants in it are introduced in descending order of score. Thus, the restaurants are introduced in the order 3,4,6,1,5,2.

Sample Input 2

10
yakutsk 10
yakutsk 20
yakutsk 30
yakutsk 40
yakutsk 50
yakutsk 60
yakutsk 70
yakutsk 80
yakutsk 90
yakutsk 100

Sample Output 2

10
9
8
7
6
5
4
3
2
1


local n,m=io.read("n","n")
local s={}
for i=1,m do
    local k=io.read("n")
    s[i]={}
    for j=1,k do
        s[i][j]=io.read("n")-1
    end
end
local p={}
for i=1,m do
    p[i]=io.read("n")
end

local counter=0
for bit=0,(1<<n)-1 do
    local checker=true
    for i=1,m do
        local onoff=0
        for _,v in pairs(s[i]) do
            onoff=onoff+(bit&(1<<v)>0 and 1 or 0)
        end
        if onoff%2~=p[i] then
            checker=false
        end
    end
    counter=counter+(checker and 1 or 0)
end
print(counter)

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

2 3
2 1 2
1 1
1 2
0 0 1

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


local DBG = false
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 N, Kmax = io.read("n", "n")
local V = {}
for i=1,N do
    V[i] = io.read("n")
end

local lim_left = math.min(N, Kmax)
local ans = 0
for a=0, lim_left do
    local got_left = {}
    local lim_right = math.min(N-a, Kmax-a)
    assert(lim_right >= 0)
    for i=1,a do
        got_left[i] = V[i]
    end
    for b=0, lim_right do
        local got = {table.unpack(got_left)}
        for i=1,b do
            got[#got + 1] = V[N+1-i]
        end
        table.sort(got)
        local ndiscard = Kmax - a - b
        local ndiscard_orig = ndiscard
        assert(ndiscard >= 0)
        local value = 0
        for i=1, #got do
            if got[i] < 0 and ndiscard > 0 then
                ndiscard = ndiscard - 1
            else
                value = value + got[i]
            end
        end
        dbgpr(a, b, #got, ndiscard_orig, value)
        ans = math.max(ans, value)
    end
end
print(ans)

Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


local mfl, mce = math.floor, math.ceil
local bls, brs = bit.lshift, bit.rshift
local mmi, mma = math.min, math.max
local n = io.read("*n")
local t = {}
_u = io.read("*n")
for i = 1, n - 1 do
  t[i] = io.read("*n")
end
n = n - 1
local ret = 0
local lim = brs(n - 1, 1)
for i = 1, n do
  local lim2 = mfl(lim / i)
  local c = 0
  for j = 1, n do
    if n % i == 0 then
      if n - i * j <= i * j then break end
    end
    if n - i * j < i then break end
    c = c + t[i * j] + t[n - i * j]
    ret = mma(ret, c)
  end
end
print(ret)

Score : 600 points

Problem Statement

There is an infinitely large pond, which we consider as a number line.
In this pond, there are N lotuses floating at coordinates 0, 1, 2, ..., N-2 and N-1.
On the lotus at coordinate i, an integer s_i is written.

You are standing on the lotus at coordinate 0. You will play a game that proceeds as follows:

1. Choose positive integers A and B. Your score is initially 0.

2. Let x be your current coordinate, and y = x+A. The lotus at coordinate x disappears, and you move to coordinate y.

If y = N-1, the game ends.

If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.

If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.

3. Let x be your current coordinate, and y = x-B. The lotus at coordinate x disappears, and you move to coordinate y.

If y = N-1, the game ends.

If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y.

If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends.

4. Go back to step 2.

You want to end the game with as high a score as possible.
What is the score obtained by the optimal choice of A and B?

Constraints

3 \leq N \leq 10^5

-10^9 \leq s_i \leq 10^9

s_0=s_{N-1}=0

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
s_0 s_1 ...... s_{N-1}

Output

Print the score obtained by the optimal choice of A and B.

Sample Input 1

5
0 2 5 1 0

Sample Output 1

3

If you choose A = 3 and B = 2, the game proceeds as follows:

Move to coordinate 0 + 3 = 3. Your score increases by s_3 = 1.

Move to coordinate 3 - 2 = 1. Your score increases by s_1 = 2.

Move to coordinate 1 + 3 = 4. The game ends with a score of 3.

There is no way to end the game with a score of 4 or higher, so the answer is 3. Note that you cannot land the lotus at coordinate 2 without drowning later.

Sample Input 2

6
0 10 -7 -4 -13 0

Sample Output 2

0

The optimal strategy here is to land the final lotus immediately by choosing A = 5 (the value of B does not matter).

Sample Input 3

11
0 -4 0 -99 31 14 -15 -39 43 18 0

Sample Output 3

59


local a, b = io.read("n", "n")
if a >= 13 then
    print(b)
elseif a >= 6 then
    print(b//2)
else
    print(0)
end

Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.


N, M = io.read("*n", "*n", "*l")
L_max = 0
R_min = 10^5
for i = 1, M do
    L, R = io.read("*n", "*n", "*l")
    if L <= R_min then
        L_max = math.max(L, L_max)
    end
    if R >= L_max then
        R_min = math.min(R, R_min)
    end
end
print(string.format("%d", R_min-L_max+1))

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


N, M = io.read("*n", "*n", "*l")
L_max = 0
R_min = 10^5
for i = 1, M do
    L, R = io.read("*n", "*n", "*l")
    if L < R_min then
        L_max = math.max(L, L_max)
    elseif R > L_max then
        R_min = math.min(R, R_min)
    end
end
print(string.format("%d", R_min-L_max+1))


--url:https://gist.github.com/LukeMS/89dc587abd786f92d60886f4977b1953
--[[  Priority Queue implemented in lua, based on a binary heap.
Copyright (C) 2017 Lucas de Morais Siqueira <lucas.morais.siqueira@gmail.com>
License: zlib
  This software is provided 'as-is', without any express or implied
  warranty. In no event will the authors be held liable for any damages
  arising from the use of this software.
  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:
  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgement in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
]]--

local floor = math.floor

local PriorityQueue = {}
PriorityQueue.__index = PriorityQueue

setmetatable(
    PriorityQueue,
    {
        __call = function (self)
            setmetatable({}, self)
            self:initialize()
            return self
        end
    }
)

function PriorityQueue:initialize()
    --[[  Initialization.
    Example:
        PriorityQueue = require("priority_queue")
        pq = PriorityQueue()
    ]]--
    self.heap = {}
    self.current_size = 0
end

function PriorityQueue:empty()
    return self.current_size == 0
end

function PriorityQueue:size()
    return self.current_size
end

function PriorityQueue:swim()
    -- Swim up on the tree and fix the order heap property.
    local heap = self.heap
    local floor = floor
    local i = self.current_size

    while floor(i / 2) > 0 do
        local half = floor(i / 2)
        if heap[i][2] < heap[half][2] then
            heap[i], heap[half] = heap[half], heap[i]
        end
        i = half
    end
end

function PriorityQueue:put(v, p)
    --[[ Put an item on the queue.
    Args:
        v: the item to be stored
        p(number): the priority of the item
    ]]--
    --

    self.heap[self.current_size + 1] = {v, p}
    self.current_size = self.current_size + 1
    self:swim()
end

function PriorityQueue:sink()
    -- Sink down on the tree and fix the order heap property.
    local size = self.current_size
    local heap = self.heap
    local i = 1

    while (i * 2) <= size do
        local mc = self:min_child(i)
        if heap[i][2] > heap[mc][2] then
            heap[i], heap[mc] = heap[mc], heap[i]
        end
        i = mc
    end
end

function PriorityQueue:min_child(i)
    if (i * 2) + 1 > self.current_size then
        return i * 2
    else
        if self.heap[i * 2][2] < self.heap[i * 2 + 1][2] then
            return i * 2
        else
            return i * 2 + 1
        end
    end
end

function PriorityQueue:pop()
    -- Remove and return the top priority item
    local heap = self.heap
    local retval = heap[1][1]
    heap[1] = heap[self.current_size]
    heap[self.current_size] = nil
    self.current_size = self.current_size - 1
    self:sink()
    return retval
end

--return PriorityQueue

local n,m=io.read("*n","*n")
local a=PriorityQueue()
for i=1,n do
    local x=io.read("*n")
    a:put(x,x)
end

local bc={}
for i=1,m do
    bc[i]={io.read("*n","*n")}
end
table.sort(bc,function(x,y)
    return x[2]>y[2]
end)

local d={}
local i=1
while #d<n do
    if bc[i]==nil then
        break
    end
    local b,c=bc[i][1],bc[i][2]
    for j=#d+1,#d+b do
        d[j]=c
    end
    i=i+1
end

for i=1,n do
    if d[i]~=nil then
        local q=a:pop()
        if q>=d[i] then
            a:put(q,q)
            break
        else
            a:put(d[i],d[i])
        end
    else
        break
    end
end

local max=0
for i=1,n do
    max=max+a:pop()
end
print(string.format("%d",max))

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

The output may not fit into a 32-bit integer type.


local N, M = io.read("n", "n")
local A = {}
for i=1,N do
    A[i] = io.read("n")
end
local T = {}
for i=1,M do
    local b, c = io.read("n", "n")
    T[i] = {b, c}
end
table.sort(A)
table.sort(T, function(x, y) return x[2] > y[2] end)

local card_idx = 1
for i=1, M do
    local b, c = table.unpack(T[i])
    for j = card_idx, math.min(card_idx + b - 1, N) do
        if A[j] < c then
            A[j] = c
        end
    end
    card_idx = card_idx + b
end

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


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

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

local ior = io.input()
local q = ior:read("*n")
local aall = {}
local ball = 0
local z, a, b = ior:read("*n", "*n", "*n")
ball = b

local leftsum = a
local rightsum = 0

table.insert(aall, a)
local cnt = 1
for i = 2, q do
  local t = ior:read("*n")
  if t == 1 then
    local a, b = ior:read("*n", "*n")
    ball = ball + b
    local inspos = lower_bound(aall, a)
    if cnt % 2 == 1 then
      local centerpos = (cnt + 1) // 2
      if centerpos < inspos then
        rightsum = rightsum + a
      else
        leftsum = leftsum + a - aall[centerpos]
        rightsum = rightsum + aall[centerpos]
      end
    else
      local cpos = 1 + cnt // 2
      if cpos < inspos then
        leftsum = leftsum + aall[cpos]
        rightsum = rightsum + a - aall[cpos]
      else
        leftsum = leftsum + a
      end
    end
    table.insert(aall, inspos, a)
    cnt = cnt + 1
  else
    local outpos = (cnt + 1) // 2
    local x = aall[outpos]
    local val = cnt % 2 == 1 and x or 0
    print(x .. " " .. val + rightsum - leftsum + ball)
  end
end

Score : 600 points

Problem Statement

There is a function f(x), which is initially a constant function f(x) = 0.

We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:

An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).

An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.

We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

Constraints

All values in input are integers.

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

-10^9 \leq a, b \leq 10^9

The first query is an update query.

Input

Input is given from Standard Input in the following format:

Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

Output

For each evaluation query, print a line containing the response, in the order in which the queries are given.

The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

Sample Input 1

4
1 4 2
2
1 1 -8
2

Sample Output 1

4 2
1 -3

In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.

In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.

Sample Input 2

4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2

Sample Output 2

-1000000000 3000000000


local function str2tbl(s)
    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 N, K, _, S = io.read("n", "n", "l", "l")
S = str2tbl(S)
S[K] = string.char(string.byte(S[K]) + 0x20)
print(table.concat(S, ""))

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


s = io.read()
s1 = tonumber(s:sub(1, 2))
s2 = tonumber(s:sub(3, 4))
f1 = 0 < s1 and s1 <= 12
f2 = 0 < s2 and s2 <= 12
if f1 and f2 then
  print("AMBIGUOUS")
elseif f1 then
  print("MMYY")
elseif f2 then
  print("YYMM")
else
  print("NA")
end

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


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

local ceil = math.ceil
local log = math.log
local function getx(n)
    return ceil(log(K/n, 2))
end

local ans = 0.0

local head_win_limit = math.min(K-1, N)
for n=1, head_win_limit do
    local x = getx(n)
    --print(n, x)
    ans = ans + (1.0/N) * ((1.0/2.0) ^ x)
end

if N-K+1 > 0 then
    ans = ans + (N-K+1.0)/N
end
print(ans)

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


local List = {}
function List.new ()
    return {first = 0, last = -1}
end

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

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

function List.popleft (list)
    local first = list.first
    local value = list[first]
    list[first] = nil
    list.first = first + 1
    return value
end

function List.popright (list)
    local last = list.last
    local value = list[last]
    list[last] = nil
    list.last = last - 1
    return value
end

function List.empty (list)
    return list.first > list.last
end

----------

local n=io.read("n")
local graph={}
for i=1,n do
    graph[i]={}
end
for i=1,n-1 do
    local u,v,w=io.read("n","n","n")
    graph[u][v]=w
    graph[v][u]=w
end

local stack=List.new()
List.pushright(stack,{1,0})
local checked={}
local color={0}

while not List.empty(stack) do
    local pop=List.popright(stack)
    local u=pop[1]
    local w=pop[2]
    checked[u]=true
    for v,_ in pairs(graph[u]) do
        if not checked[v] then
            local nw=w+graph[u][v]
            color[v]=nw%2
            List.pushright(stack,{v,nw})
        end
    end
end

for i=1,n do
    print(color[i])
end

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

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

Sample Output 2

1
0
1
0
1


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 use_strict()
    local mt = {
        __index = function(t,k) error("_G __index:" .. k) end,
        __newindex = function(t,k,v) error("_G __newindex:" .. k) end
    }
    setmetatable(_G, mt)
end

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

--[[
function List:pushleft(value)
    local first = self.first - 1
    self.first = first
    self[first] = value
end
]]

function List:pushright(value)
    local last = self.last + 1
    self.last = last
    self[last] = value
end

function List:popleft()
    local first = self.first
    if first > self.last then error("list is empty") end
    local value = self[first]
    self[first] = nil        -- to allow garbage collection
    self.first = first + 1
    return value
end

--[[
function List:popright()
    local last = self.last
    if self.first > last then error("list is empty") end
    local value = self[last]
    self[last] = nil         -- to allow garbage collection
    self.last = last - 1
    return value
end
]]

function List:count()
    return self.last - self.first + 1
end
--
use_strict()
local N = io.read("n")
local weights = {}
local adj_list = {}
for i=1,N do
    adj_list[i] = {}
end
local function key(u,v)
    return u .. "," .. v
end
local function getw(u,v)
    return weights[key(u,v)] or weights[key(v,u)]
end
for i=1,N-1 do
    local u,v,w = io.read("n", "n", "n")
    weights[key(u,v)] = w
    table.insert(adj_list[u], v)
    table.insert(adj_list[v], u)
end

local distance_from_1 = {}
distance_from_1[1] = 0
do
    local seen = {}
    seen[1] = true
    local accum = 0
    local q = List.new()
    q:pushright(1)
    local count = 1
    while count < N do
        local from = q:popleft()
        local w_before = distance_from_1[from]
        for _, to in ipairs(adj_list[from]) do
            if not seen[to] then
                seen[to] = true
                local w = getw(from, to)
                distance_from_1[to] = w_before + w
                count = count + 1
                q:pushright(to)
            end
        end
    end
end
--dbgpr_t(distance_from_1)
for i=1,N do
    if distance_from_1[i] % 2 == 0 then
        print(0)
    else
        print(1)
    end
end


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

local function uf_findroot(idx)
  local idx_update = idx
  while parent[idx] ~= idx do
    idx = parent[idx]
  end
  while parent[idx_update] ~= idx do
    parent[idx_update], idx_update = idx, parent[idx_update]
  end
  return idx
end

for i = 1, m do
  local x, y, _z = io.read("*n", "*n", "*n")
  local xp, yp = uf_findroot(x), uf_findroot(y)
  parent[yp], parent[y] = xp, xp
end

local c = 0
local map = {}
for i = 1, n do
  local p = uf_findroot(i)
  if not map[p] then
    c = c + 1
    map[p] = true
  end
end
print(c)

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


local ior = io.input()
local n, m = ior:read("*n", "*n")

local parent = {}
local groupsize = {}
for i = 1, n do parent[i] = i end
for i = 1, n do groupsize[i] = 1 end

local function getroot(idx)
  while(parent[idx] ~= idx) do
    idx = parent[idx]
  end
  return idx
end

for i = 1, m do
  local x, y, z = ior:read("*n", "*n", "*n")
  local xroot, yroot = getroot(x), getroot(y)
  if(groupsize[xroot] < groupsize[yroot]) then
    groupsize[yroot] = groupsize[xroot] + groupsize[yroot]
    parent[x] = yroot
    parent[xroot] = yroot
    parent[y] = yroot
  else
    groupsize[xroot] = groupsize[xroot] + groupsize[yroot]
    parent[x] = xroot
    parent[yroot] = xroot
    parent[y] = xroot
  end
end
local grouplist = {}
local cnt = 0
for i = 1, n do
  local r = getroot(i)
  if(grouplist[r] == nil) then
    grouplist[r] = true
    cnt = cnt + 1
  end
end
print(cnt)


a, b, c, n = io.read("*n", "*n", "*n", "*n")
t = {}
for i = 1, n + 1 do
  t[i] = 0
end
-- f(x) * (1-x^a)(1-x^b)(1-x^c) = 1
t[1] = 1
for i = 2, n + 1 do
  v = 0
  if a < i then v = v - t[i - a] end
  if b < i then v = v - t[i - b] end
  if c < i then v = v - t[i - c] end
  if a + b < i then v = v + t[i - a - b] end
  if b + c < i then v = v + t[i - b - c] end
  if c + a < i then v = v + t[i - c - a] end
  if a + b + c < i then v = v - t[i - a - b - c] end
  t[i] = -v
end
print(t[n + 1])

Score : 200 points

Problem Statement

Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:

Red boxes, each containing R red balls

Green boxes, each containing G green balls

Blue boxes, each containing B blue balls

Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes.
How many triples of non-negative integers (r,g,b) achieve this?

Constraints

All values in input are integers.

1 \leq R,G,B,N \leq 3000

Input

Input is given from Standard Input in the following format:

R G B N

Output

Print the answer.

Sample Input 1

1 2 3 4

Sample Output 1

4

Four triples achieve the objective, as follows:

(4,0,0)

(2,1,0)

(1,0,1)

(0,2,0)

Sample Input 2

13 1 4 3000

Sample Output 2

87058


r,g,b,n=io.read("*n","*n","*n","*n")

counter=0
for i=0,n do
    for j=0,n do
        rg=r*i+g*j
        if n>=rg and (n-rg)%b==0 then
            counter=counter+1
        end
    end
end
print(counter)


r,g,b,n=io.read("*n","*n","*n","*n")

counter=0
for i=0,3000 do
    for j=0,3000 do
        rg=r*i+g*j
        if n>=rg and (n-rg)%b==0 then
            counter=counter+1
        end
    end
end
print(counter)


local R,G,B,N = io.read("n", "n", "n", "n")

local cnt = 0
for r=0,N do
    local lim = (N - R*r) / G
    --print(lim)
    for g=0,lim do
        local b = (N - R*r - G*g) / B
        if b >= 0 and b == math.floor(b) then
            cnt = cnt + 1
            --print(r,g,b)
        end
    end
end
print(cnt)


local counter=0
local BA,B_,_A=0,0,0
local n=io.read("n","l")
for i=1,n do
    local s=io.read()
    local _,sAB=s:gsub("AB","")
    counter=counter+sAB
    sf=s:sub(1,1)
    sl=s:sub(#s,#s)
    BA=((sf=="B" and sl=="A") and BA+1 or BA)
    B_=((sf=="B" and sl~="A") and B_+1 or B_)
    _A=((sf~="B" and sl=="A") and _A+1 or _A)
end

if BA==0 then
    counter=counter+math.min(B_,_A)
elseif BA>0 and B_+_A>0 then
    counter=counter+BA+math.min(B_,_A)
elseif BA>0 and B_+_A==0 then
    counter=counter+BA-1
end
print(counter)

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


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

local N = io.read("n")
local lim = math.ceil(N^0.5)
local ans = 0
dbgpr(lim)
for k=lim,1,-1 do
    dbgpr(k)
    if N % k == 0 then
        local d = N // k
        local m = d - 1
        if m > 0 and (N // m == N % m) then
            dbgpr("OK", k, d, m)
            ans = ans + m
        end
    end
end
print(ans)

Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


local h, w, n = io.read("*n", "*n", "*n", "*l")
local sr, sc = io.read("*n", "*n", "*l")
local s = io.read()
local t = io.read()
local safe_l, safe_r, safe_t, safe_b = 1, w, 1, h
local isok = true
local mma, mmi = math.max, math.min
for i = n, 1, -1 do
  local tt = t:sub(i, i)
  if tt == "L" then
    safe_r = mmi(safe_r + 1, w)
  elseif tt == "R" then
    safe_l = mma(safe_l - 1, 1)
  elseif tt == "U" then
    safe_b = mmi(safe_b + 1, h)
  else
    safe_t = mma(safe_t - 1, 1)
  end
  local ss = s:sub(i, i)
  if ss == "L" then
    safe_l = safe_l + 1
    if safe_r < safe_l then isok = false break end
  elseif ss == "R" then
    safe_r = safe_r - 1
    if safe_r < safe_l then isok = false break end
  elseif ss == "U" then
    safe_t = safe_t + 1
    if safe_b < safe_t then isok = false break end
  else
    safe_b = safe_b - 1
    if safe_b < safe_t then isok = false break end
  end
  if not isok then break end
end
if isok then
  isok = safe_t <= sr and sr <= safe_b and safe_l <= sc and sc <= safe_r
end
print(isok and "YES" or "NO")

Score : 600 points

Problem Statement

We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
On this grid, there is a piece, which is initially placed at square (s_r,s_c).

Takahashi and Aoki will play a game, where each player has a string of length N.
Takahashi's string is S, and Aoki's string is T. S and T both consist of four kinds of letters: L, R, U and D.

The game consists of N steps. The i-th step proceeds as follows:

First, Takahashi performs a move. He either moves the piece in the direction of S_i, or does not move the piece.

Second, Aoki performs a move. He either moves the piece in the direction of T_i, or does not move the piece.

Here, to move the piece in the direction of L, R, U and D, is to move the piece from square (r,c) to square (r,c-1), (r,c+1), (r-1,c) and (r+1,c), respectively. If the destination square does not exist, the piece is removed from the grid, and the game ends, even if less than N steps are done.

Takahashi wants to remove the piece from the grid in one of the N steps.
Aoki, on the other hand, wants to finish the N steps with the piece remaining on the grid.
Determine if the piece will remain on the grid at the end of the game when both players play optimally.

Constraints

2 \leq H,W \leq 2 \times 10^5

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

1 \leq s_r \leq H

1 \leq s_c \leq W

|S|=|T|=N

S and T consists of the four kinds of letters L, R, U and D.

Input

Input is given from Standard Input in the following format:

H W N
s_r s_c
S
T

Output

If the piece will remain on the grid at the end of the game, print YES; otherwise, print NO.

Sample Input 1

2 3 3
2 2
RRL
LUD

Sample Output 1

YES

Here is one possible progress of the game:

Takahashi moves the piece right. The piece is now at (2,3).

Aoki moves the piece left. The piece is now at (2,2).

Takahashi does not move the piece. The piece remains at (2,2).

Aoki moves the piece up. The piece is now at (1,2).

Takahashi moves the piece left. The piece is now at (1,1).

Aoki does not move the piece. The piece remains at (1,1).

Sample Input 2

4 3 5
2 2
UDRRR
LLDUD

Sample Output 2

NO

Sample Input 3

5 6 11
2 1
RLDRRUDDLRL
URRDRLLDLRD

Sample Output 3

NO