local mmi, mma = math.min, math.max
local n, t = io.read("*n", "*n")
local a = {}
for i = 1, n do
  a[i] = io.read("*n")
end
local maxdiff = 0
local maxdiff_cnt = 0
local curmin = a[1]
for i = 2, n do
  if curmin < a[i] then
    if maxdiff < a[i] - curmin then
      maxdiff = a[i] - curmin
      maxdiff_cnt = 1
    elseif maxdiff == a[i] - curmin then
      maxdiff_cnt = maxdiff_cnt + 1
    end
  end
  curmin = mmi(curmin, a[i])
end
print(maxdiff_cnt)

Score : 400 points

Problem Statement

There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.

Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town i (i < N), move to town i + 1.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.

Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

A_i are distinct.

2 ≦ T ≦ 10^9

In the initial state, Takahashi's expected profit is at least 1 yen.

Input

The input is given from Standard Input in the following format:

N T
A_1 A_2 ... A_N

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:

Move from town 1 to town 2.

Buy one apple for 50 yen at town 2.

Move from town 2 to town 3.

Sell one apple for 200 yen at town 3.

If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

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

Sample Output 3

2


local mmi, mma = math.min, math.max
local n = io.read("*n")
local edge = {}
local len = {}
local parent = {}
local childcnt = {}
local valmin, valmax = {}, {}
for i = 1, n do
  edge[i] = {}
  len[i] = -1
  parent[i] = 0
  childcnt[i] = 0
  valmin[i], valmax[i] = false, false
end
for i = 1, n - 1 do
  local a, b = io.read("*n", "*n")
  edge[a][b], edge[b][a] = true, true
end
local k = io.read("*n")
local startpos, startval = 0, 0
for i = 1, k do
  local pos, val = io.read("*n", "*n")
  valmin[pos], valmax[pos] = val, val
  if i == 1 or val < startval then
    startpos, startval = pos, val
  end
end
local valid = true
len[startpos] = 0
local tasks = {startpos}
for i = 1, n do
  local src = tasks[i]
  for dst, _u in pairs(edge[src]) do
    if len[dst] < 0 then
      childcnt[src] = childcnt[src] + 1
      parent[dst] = src
      len[dst] = len[src] + 1
      if valmax[dst] then
        if (valmax[dst] + valmax[startpos] + len[dst]) % 2 == 1 then
          valid = false break
        end
        if valmax[startpos] + len[dst] < valmax[dst] then
          valid = false break
        end
      else
        valmax[dst] = valmax[startpos] + len[dst]
        valmin[dst] = valmax[startpos] + (len[dst] % 2)
      end
      table.insert(tasks, dst)
    end
  end
  if not valid then break end
end
if not valid then print("NO")
else
  tasks = {}
  for i = 1, n do
    if childcnt[i] == 0 then
      table.insert(tasks, i)
    end
  end
  for i = 1, n - 1 do
    local c = tasks[i]
    local p = parent[c]
    local newp_min = mma(valmin[p], valmin[c] - 1)
    local newp_max = mmi(valmax[p], valmax[c] + 1)
    if newp_max < newp_min then
      valid = false
      break
    end
    valmin[p] = newp_min
    valmax[p] = newp_max
    childcnt[p] = childcnt[p] - 1
    if childcnt[p] == 0 then
      table.insert(tasks, p)
    end
  end
  if not valid then print("NO")
  else
    local val = {}
    for i = 1, n do val[i] = 0 end
    val[startpos] = valmin[startpos]
    tasks = {startpos}
    for i = 1, n do
      local src = tasks[i]
      for dst, _u in pairs(edge[src]) do
        if len[src] < len[dst] then
          if valmin[dst] <= val[src] - 1 then
            val[dst] = val[src] - 1
          else
            val[dst] = val[src] + 1
          end
          table.insert(tasks, dst)
        end
      end
    end
    print("Yes")
    for i = 1, n do
      print(val[i])
    end
  end
end

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

Score : 800 points

Problem Statement

We have a tree with N vertices. The vertices are numbered 1, 2, ..., N. The i-th (1 ≦ i ≦ N - 1) edge connects the two vertices A_i and B_i.

Takahashi wrote integers into K of the vertices. Specifically, for each 1 ≦ j ≦ K, he wrote the integer P_j into vertex V_j. The remaining vertices are left empty. After that, he got tired and fell asleep.

Then, Aoki appeared. He is trying to surprise Takahashi by writing integers into all empty vertices so that the following condition is satisfied:

Condition: For any two vertices directly connected by an edge, the integers written into these vertices differ by exactly 1.

Determine if it is possible to write integers into all empty vertices so that the condition is satisfied. If the answer is positive, find one specific way to satisfy the condition.

Constraints

1 ≦ N ≦ 10^5

1 ≦ K ≦ N

1 ≦ A_i, B_i ≦ N (1 ≦ i ≦ N - 1)

1 ≦ V_j ≦ N (1 ≦ j ≦ K) (21:18, a mistake in this constraint was corrected)

0 ≦ P_j ≦ 10^5 (1 ≦ j ≦ K)

The given graph is a tree.

All v_j are distinct.

Input

The input is given from Standard Input in the following format:

N
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}
K
V_1 P_1
V_2 P_2
:
V_K P_K

Output

If it is possible to write integers into all empty vertices so that the condition is satisfied, print Yes. Otherwise, print No.

If it is possible to satisfy the condition, print N lines in addition. The v-th (1 ≦ v ≦ N) of these N lines should contain the integer that should be written into vertex v. If there are multiple ways to satisfy the condition, any of those is accepted.

Sample Input 1

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

Sample Output 1

Yes
5
6
6
5
7

The figure below shows the tree when Takahashi fell asleep. For each vertex, the integer written beside it represents the index of the vertex, and the integer written into the vertex is the integer written by Takahashi.

Aoki can, for example, satisfy the condition by writing integers into the remaining vertices as follows:

This corresponds to Sample Output 1. Note that other outputs that satisfy the condition will also be accepted, such as:

Yes
7
6
8
7
7

Sample Input 2

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

Sample Output 2

No

Sample Input 3

4
1 2
2 3
3 4
1
1 0

Sample Output 3

Yes
0
-1
-2
-3

The integers written by Aoki may be negative or exceed 10^6.

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 mma = math.max
local mfl, mce, mmi = math.floor, math.ceil, math.min

local AvlTree = {}
AvlTree.makenode = function(self, val, parent)
  local i = self.box[#self.box]
  if not i then i = #self.v + 1
  else table.remove(self.box)
  end
  self.v[i], self.p[i] = val, parent
  self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  return i
end
AvlTree.create = function(self, lessthan, n)
  self.lessthan = lessthan
  self.root = 1
  self.box = {}
  for i = n + 1, 2, -1 do table.insert(self.box, i) end
  -- value, leftCount, rightCount, left, right, parent
  self.v, self.lc, self.rc, self.l, self.r, self.p = {}, {}, {}, {}, {}, {}
  for i = 1, n + 1 do
    self.v[i], self.p[i] = 0, 1
    self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  end
end

AvlTree.recalc = function(self, i)
  local kl, kr = self.l[i], self.r[i]
  if 1 < kl then self.lc[i] = 1 + mma(self.lc[kl], self.rc[kl])
  else self.lc[i] = 0
  end
  if 1 < kr then self.rc[i] = 1 + mma(self.lc[kr], self.rc[kr])
  else self.rc[i] = 0
  end
end
AvlTree.recalcAll = function(self, i)
  while 1 < i do
    self:recalc(i)
    i = self.p[i]
  end
end

AvlTree.rotR = function(self, parent)
  local granp, child = self.p[parent], self.l[parent]
  self.r[child], self.l[parent] = parent, self.r[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.l[parent]] = parent
  if 1 < granp then
    if self.l[granp] == parent then
      self.l[granp] = child
    else
      self.r[granp] = child
    end
  else
    self.root = child
  end
end

AvlTree.rotL = function(self, parent)
  local granp, child = self.p[parent], self.r[parent]
  self.l[child], self.r[parent] = parent, self.l[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.r[parent]] = parent
  if 1 < granp then
    if self.r[granp] == parent then
      self.r[granp] = child
    else
      self.l[granp] = child
    end
  else
    self.root = child
  end
end

AvlTree.rotLR = function(self, lparent, rparent)
  local sp, sl, sr = self.p, self.l, self.r
  local granp, d = sp[rparent], sr[lparent]
  sp[lparent], sr[lparent] = d, sl[d]
  sp[rparent], sl[rparent] = d, sr[d]
  sp[sl[d]], sp[sr[d]] = lparent, rparent
  sp[d], sl[d], sr[d] = granp, lparent, rparent
  if 1 < granp then
    if sr[granp] == rparent then sr[granp] = d
    else sl[granp] = d
    end
  else self.root = d
  end
end

AvlTree.rotRL = function(self, rparent, lparent)
  local sp, sl, sr = self.p, self.l, self.r
  local granp, d = sp[lparent], sl[rparent]
  sp[rparent], sl[rparent] = d, sr[d]
  sp[lparent], sr[lparent] = d, sl[d]
  sp[sr[d]], sp[sl[d]] = rparent, lparent
  sp[d], sr[d], sl[d] = granp, rparent, lparent
  if 1 < granp then
    if sl[granp] == lparent then sl[granp] = d
    else sr[granp] = d
    end
  else self.root = d
  end
end

AvlTree.empty = function(self) return self.root <= 1 end

AvlTree.push = function(self, val)
  if self.root <= 1 then self.root = self:makenode(val, 1) return end
  local pos = self.root
  while true do
    if self.lessthan(val, self.v[pos]) then
      if 1 < self.l[pos] then
        pos = self.l[pos]
      else
        self.l[pos] = self:makenode(val, pos)
        pos = self.l[pos]
        break
      end
    else
      if 1 < self.r[pos] then
        pos = self.r[pos]
      else
        self.r[pos] = self:makenode(val, pos)
        pos = self.r[pos]
        break
      end
    end
  end
  while 1 < pos do
    local child, parent = pos, self.p[pos]
    if parent <= 1 then
      break
    end
    self:recalc(parent)
    local lcp_m_rcp = self.lc[parent] - self.rc[parent]
    if lcp_m_rcp % 2 ~= 0 then -- 1 or -1
      pos = parent
    elseif lcp_m_rcp == 2 then
      if self.lc[child] - 1 == self.rc[child] then
        self:rotR(parent)
        self:recalcAll(parent)
      else
        self:rotLR(child, parent)
        self:recalc(child)
        self:recalcAll(parent)
      end
      break
    elseif lcp_m_rcp == -2 then
      if self.rc[child] - 1 == self.lc[child] then
        self:rotL(parent)
        self:recalcAll(parent)
      else
        self:rotRL(child, parent)
        self:recalc(child)
        self:recalcAll(parent)
      end
      break
    else
      break
    end
  end
end

AvlTree.rmsub = function(self, node)
  while 1 < node do
    self:recalc(node)
    if self.lc[node] == self.rc[node] then
      node = self.p[node]
    elseif self.lc[node] + 1 == self.rc[node] then
      self:recalcAll(self.p[node])
      break
    else
      if self.lc[self.r[node]] == self.rc[self.r[node]] then
        self:rotL(node)
        self:recalcAll(node)
        break
      elseif self.lc[self.r[node]] + 1 == self.rc[self.r[node]] then
        local nr = self.r[node]
        self:rotL(node)
        self:recalc(node)
        node = nr
      else
        local nr = self.r[node]
        local nrl = self.l[nr]
        self:rotRL(nr, node)
        self:recalc(nr)
        self:recalc(node)
        node = nrl
      end
    end
  end
end

AvlTree.pop = function(self)
  local node = self.root
  while 1 < self.l[node] do
    node = self.l[node]
  end
  local v = self.v[node]
  local kp = self.p[node]
  self.p[self.r[node]] = kp
  if 1 < kp then
    self.l[kp] = self.r[node]
    self:rmsub(kp)
  else
    self.root = self.r[node]
  end
  table.insert(self.box, node)
  return v
end

AvlTree.new = function(lessthan, n)
  local obj = {}
  setmetatable(obj, {__index = AvlTree})
  obj:create(lessthan, n)
  return obj
end

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

local function lt(p, q)
  return a[p] > a[q]
end
local avl = AvlTree.new(lt, m)
for i = 1, m do avl:push(i) end
while true do
  local top = avl:pop()
  if avl:empty() then
    print(a[top] - 1)
    break
  else
    local nxt = avl:pop()
    a[top] = a[top] - 1
    a[nxt] = a[nxt] - 1
    if 0 < a[nxt] then
      avl:push(nxt)
      avl:push(top)
    elseif 0 < a[top] then
      avl:push(top)
    end
  end
end

Score : 200 points

Problem Statement

There are K pieces of cakes.
Mr. Takahashi would like to eat one cake per day, taking K days to eat them all.

There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i.

Eating the same type of cake two days in a row would be no fun,
so Mr. Takahashi would like to decide the order for eating cakes that minimizes the number of days on which he has to eat the same type of cake as the day before.

Compute the minimum number of days on which the same type of cake as the previous day will be eaten.

Constraints

1 ≤ K ≤ 10000

1 ≤ T ≤ 100

1 ≤ a_i ≤ 100

a_1 + a_2 + ... + a_T = K

Input

The input is given from Standard Input in the following format:

K T
a_1 a_2 ... a_T

Output

Print the minimum number of days on which the same type of cake as the previous day will be eaten.

Sample Input 1

7 3
3 2 2

Sample Output 1

0

For example, if Mr. Takahashi eats cakes in the order of 2, 1, 2, 3, 1, 3, 1, he can avoid eating the same type of cake as the previous day.

Sample Input 2

6 3
1 4 1

Sample Output 2

1

There are 6 cakes.
For example, if Mr. Takahashi eats cakes in the order of 2, 3, 2, 2, 1, 2, he has to eat the same type of cake (i.e., type 2) as the previous day only on the fourth day.
Since this is the minimum number, the answer is 1.

Sample Input 3

100 1
100

Sample Output 3

99

Since Mr. Takahashi has only one type of cake, he has no choice but to eat the same type of cake as the previous day from the second day and after.


local k,t=io.read("n","n","l")
local a_max=0
for i=1,t do
    local a=io.read("n")
    a_max=math.max(a_max,a)
end
print(math.max(a_max-1-(k-a_max),0))


a,b,c=io.read():match("(.+)%s(.+)%s(.+)")
ans=0
for i=1,100 do
  ans=ans+((a*1==i or b*1==i or c*1==i) and 1 or 0)
end
print(ans)

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

The input is given from Standard Input in the following format:

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

The input is given from Standard Input in the following format:

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


local w, h = io.read("*n", "*n")
local wuse, huse = 0, 0
local t = {}
local idx = {}
for i = 1, w + h do
  t[i] = io.read("*n")
  idx[i] = i
end
table.sort(idx, function(a, b) return t[a] < t[b] end)
local ret = 0
local rem = (w + 1) * (h + 1) - 1
for i = 1, w + h do
  local src = idx[i]
  if src <= w then
    local use = h + 1 - huse
    if rem < use then use = rem end
    ret = ret + use * t[src]
    wuse = wuse + 1
    rem = rem - use
  else
    local use = w + 1 - wuse
    if rem < use then use = rem end
    ret = ret + use * t[src]
    huse = huse + 1
    rem = rem - use
  end
  if rem == 0 then break end
end
print(ret)

Score : 500 points

Problem Statement

On an xy plane, in an area satisfying 0 ≤ x ≤ W, 0 ≤ y ≤ H, there is one house at each and every point where both x and y are integers.

There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the y coordinates are equal and the difference between the x coordinates is 1.

The cost of paving a road between houses on coordinates (i,j) and (i+1,j) is p_i for any value of j, while the cost of paving a road between houses on coordinates (i,j) and (i,j+1) is q_j for any value of i.

Mr. Takahashi wants to pave some of these roads and be able to travel between any two houses on paved roads only. Find the solution with the minimum total cost.

Constraints

1 ≦ W,H ≦ 10^5

1 ≦ p_i ≦ 10^8(0 ≦ i ≦ W-1)

1 ≦ q_j ≦ 10^8(0 ≦ j ≦ H-1)

p_i (0 ≦ i ≦ W−1) is an integer.

q_j (0 ≦ j ≦ H−1) is an integer.

Input

Inputs are provided from Standard Input in the following form.

W H
p_0
:
p_{W-1}
q_0
:
q_{H-1}

Output

Output an integer representing the minimum total cost.

Sample Input 1

2 2
3
5
2
7

Sample Output 1

29

It is enough to pave the following eight roads.

Road connecting houses at (0,0) and (0,1)

Road connecting houses at (0,1) and (1,1)

Road connecting houses at (0,2) and (1,2)

Road connecting houses at (1,0) and (1,1)

Road connecting houses at (1,0) and (2,0)

Road connecting houses at (1,1) and (1,2)

Road connecting houses at (1,2) and (2,2)

Road connecting houses at (2,0) and (2,1)

Sample Input 2

4 3
2
4
8
1
2
9
3

Sample Output 2

60


local x=io.read()
local y=0
for k,v in x:gmatch("%bST") do
    y=y+#k
end
print(#x-y)

Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

The input is given from Standard Input in the following format:

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


local X = io.read()

local function main(str)
	local sPos = string.find(str, "ST")
	if sPos then
		local ePos = sPos + 1
		local leftStr = string.sub(str, 1, sPos - 1)
		local rightStr = string.sub(str, ePos + 1, string.len(str))
		str = leftStr .. rightStr
		return main(str)
	end
	print(string.len(str))
end

main(X)


s = io.read()

local function solve()
	local n = #s
	while true do
		s = string.gsub(s, "ST", "")
		if #s == n then
			return n
		end
		n = #s
	end
	return 0
end
print(solve())


local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegTree = {}
SegTree.create = function(self, ary, func, emptyvalue)
  self.n, self.func, self.emptyvalue = #ary, func, emptyvalue
  local stagenum, mul = 1, 1
  self.cnt, self.stage, self.size = {1}, {{}}, {}
  while mul < self.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, self.n do
    self.stage[stagenum][i] = ary[i]
  end
  for i = self.n + 1, mul do
    self.stage[stagenum][i] = emptyvalue
  end
  for i = stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = func(self.stage[i + 1][j * 2 - 1], self.stage[i + 1][j * 2])
    end
  end
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 tasks = {{start_stage, left, right}}
  while 0 < #tasks do
    local task = tasks[#tasks]
    table.remove(tasks)
    local stage, l, r = task[1], task[2], task[3]
    if (l - 1) % self.size[stage] ~= 0 then
      local newr = mce((l - 1) / self.size[stage]) * self.size[stage]
      table.insert(tasks, {stage + 1, l, mmi(r, newr)})
      l = newr + 1
    end
    if self.size[stage] <= r + 1 - l then
      local pos = mce(l / self.size[stage])
      ret = self.func(ret, self.stage[stage][pos])
      l = l + self.size[stage]
    end
    if l <= r then
      table.insert(tasks, {stage + 1, l, r})
    end
  end
  return ret
end

SegTree.new = function(ary, func, emptyvalue)
  local obj = {}
  setmetatable(obj, {__index = SegTree})
  obj:create(ary, func, emptyvalue)
  return obj
end

local n = io.read("*n", "*l")
local str = io.read()
local t = {}
local idx = 1
for v in str:gmatch("%d+") do
  table.insert(t, {idx, tonumber(v)})
  idx = idx + 1
end
local segtree = SegTree.new(t, function(a, b) return a[2] < b[2] and a or b end, {0, n + 1})
local tasks = {{1, n}}
local ret1, ret2 = 0, 0
local big = 1000000000
while 0 < #tasks do
  local l, r = tasks[#tasks][1], tasks[#tasks][2]
  table.remove(tasks)
  local p = segtree:getRange(l, r)
  local val = p[2] * (p[1] + 1 - l) * (r + 1 - p[1])
  ret2 = ret2 + val
  ret1, ret2 = ret1 + mfl(ret2 / big), ret2 % big
  if p[1] ~= l then
    table.insert(tasks, {l, p[1] - 1})
  end
  if p[1] ~= r then
    table.insert(tasks, {p[1] + 1, r})
  end
end
ret2 = 0 < ret1 and string.format("%09d", ret2) or ret2
ret1 = 0 < ret1 and ret1 or ""
print(ret1 .. ret2)

Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the answer.

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

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85


local s=io.read()
local sable={s:byte(1,#s)}
local k=io.read("n")
for i=1,#s do
    local a=sable[i]-96
    if k>=(27-a) then
        k=k-(27-a)
        a=a+(27-a)
        sable[i]=string.char(a%26+96)
    elseif i==#s then
        a=a+k
        sable[i]=string.char(a%27+96)
    else
        sable[i]=string.char(sable[i])
    end
end
print(table.concat(sable,""))

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


local a, b, h = io.read("*n", "*n", "*n")
print(string.format("%d", (a + b) * h / 2))

Score : 100 points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

The input is given from Standard Input in the following format:

a
b
h

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.


a=io.read()
b=io.read()
c=io.read()
print(math.floor((a+b)*c/2))


local S={}
S["a"]=io.read()
S["b"]=io.read()
S["c"]=io.read()

local discard="a"
while true do
    if #S[discard]==0 then
        print(discard:upper())
        break
    end
    discard,S[discard]=S[discard]:sub(1,1),S[discard]:sub(2)
end

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

The input is given from Standard Input in the following format:

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


local S={}
S["a"]=io.read()
S["b"]=io.read()
S["c"]=io.read()

local discard="a"
while true do
    discard=S[discard]:sub(1,1)
    S[discard]=S[discard]:sub(2)
    if S[discard]=="" then
        print(discard:upper())
        break
    end
end


local s=io.read()
local n=#s
local sum=0
for bit=0,(1<<(n-1))-1 do
    local tmp=0
    for i=1,n-1 do
        tmp=tmp*10
        tmp=tmp+s:byte(i)-48
        if bit&(1<<(i-1))>0 then
            sum=sum+tmp
            tmp=0
        end
    end
    tmp=tmp*10
    tmp=tmp+s:byte(n)-48
    sum=sum+tmp
end
print(sum)

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

The input is given from Standard Input in the following format:

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944


local h, w, n = io.read("*n", "*n", "*n")
local t = {}

local function add(i_h, i_w)
  if not t[i_h] then t[i_h] = {} end
  local v = t[i_h][i_w]
  if v then t[i_h][i_w] = v + 1 else t[i_h][i_w] = 1 end
end

local function subtask(ah, bw)
  if 3 <= bw then add(ah, bw - 2) end
  if 2 <= bw and bw < w then add(ah, bw - 1) end
  if bw < w - 1 then add(ah, bw) end
end

for i = 1, n do
  local ah, bw = io.read("*n", "*n")
  if 3 <= ah then subtask(ah - 2, bw) end
  if 2 <= ah and ah  < h then subtask(ah - 1, bw) end
  if ah < h - 1 then subtask(ah, bw) end
end

local sum = 0
local tbl = {}
for i = 1, 9 do tbl[i] = 0 end
for k, v in pairs(t) do
  for k2, v2 in pairs(v) do
    tbl[v2] = tbl[v2] + 1
    sum = sum + 1
  end
end
local rem = (h - 2LL) * (w - 2LL) - sum
local str = tostring(rem):gsub("LL", "")
print(str)
for i = 1, 9 do print(tbl[i]) end

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. At first, all cells were painted white.

Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.

Compute the following:

For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the grid contains exactly j black cells, after Snuke painted N cells?

Constraints

3 \leq H \leq 10^9

3 \leq W \leq 10^9

0 \leq N \leq min(10^5,H×W)

1 \leq a_i \leq H (1 \leq i \leq N)

1 \leq b_i \leq W (1 \leq i \leq N)

(a_i, b_i) \neq (a_j, b_j) (i \neq j)

Input

The input is given from Standard Input in the following format:

H W N
a_1 b_1
:
a_N b_N

Output

Print 10 lines.
The (j+1)-th ( 0 \leq j \leq 9 ) line should contain the number of the subrectangles of size 3×3 of the grid that contains exactly j black cells.

Sample Input 1

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

Sample Output 1

0
0
0
2
4
0
0
0
0
0

There are six subrectangles of size 3×3. Two of them contain three black cells each, and the remaining four contain four black cells each.

Sample Input 2

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

Sample Output 2

4
26
22
10
2
0
0
0
0
0

Sample Input 3

1000000000 1000000000 0

Sample Output 3

999999996000000004
0
0
0
0
0
0
0
0
0


local h, w, n = io.read("*n", "*n", "*n")
local t = {}

local function add(i_h, i_w)
  local idx = i_h .. ":" .. i_w --(i_h - 1) * 1000000000 + i_w
  if t[idx] then t[idx] = t[idx] + 1 else t[idx] = 1 end
end

local function subtask(ah, bw)
  if 3 <= bw then add(ah, bw - 2) end
  if 2 <= bw and bw < w then add(ah, bw - 1) end
  if bw < w - 1 then add(ah, bw) end
end

for i = 1, n do
  local ah, bw = io.read("*n", "*n")
  if 3 <= ah then subtask(ah - 2, bw) end
  if 2 <= ah and ah  < h then subtask(ah - 1, bw) end
  if ah < h - 1 then subtask(ah, bw) end
end

local sum = 0
local tbl = {}
for i = 1, 9 do tbl[i] = 0 end
for k, v in pairs(t) do
  tbl[v] = tbl[v] + 1
  sum = sum + 1
end
local rem = (h - 2) * (w - 2) - sum
print(rem)
for i = 1, 9 do print(tbl[i]) end


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

local AvlTree = {}
AvlTree.makenode = function(self, val, parent)
  local i = self.box[#self.box]
  table.remove(self.box)
  self.v[i], self.p[i] = val, parent
  self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  return i
end
AvlTree.create = function(self, lessthan, n)
  self.lessthan = lessthan
  self.root = 1
  self.box = {}
  for i = n + 1, 2, -1 do table.insert(self.box, i) end
  -- value, leftCount, rightCount, left, right, parent
  self.v, self.lc, self.rc, self.l, self.r, self.p = {}, {}, {}, {}, {}, {}
  for i = 1, n + 1 do
    self.v[i], self.p[i] = 0, 1
    self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 1, 1
  end
end

AvlTree.recalcCount = function(self, i)
  if 1 < i then
    if 1 < self.l[i] then self.lc[i] = 1 + mma(self.lc[self.l[i]], self.rc[self.l[i]])
    else self.lc[i] = 0
    end
    if 1 < self.r[i] then self.rc[i] = 1 + mma(self.lc[self.r[i]], self.rc[self.r[i]])
    else self.rc[i] = 0
    end
  end
end
AvlTree.recalcCountAll = function(self, i)
  while 1 < i do
    self:recalcCount(i)
    i = self.p[i]
  end
end

AvlTree.rotR = function(self, child, parent)
  local granp = self.p[parent]
  self.r[child], self.l[parent] = parent, self.r[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.l[parent]] = parent
  if 1 < granp then
    if self.l[granp] == parent then
      self.l[granp] = child
    else
      self.r[granp] = child
    end
  else
    self.root = child
  end
  self:recalcCountAll(parent)
end

AvlTree.rotL = function(self, child, parent)
  local granp = self.p[parent]
  self.l[child], self.r[parent] = parent, self.l[child]
  self.p[child], self.p[parent] = granp, child
  self.p[self.r[parent]] = parent
  if 1 < granp then
    if self.r[granp] == parent then
      self.r[granp] = child
    else
      self.l[granp] = child
    end
  else
    self.root = child
  end
  self:recalcCountAll(parent)
end

AvlTree.add = function(self, val)
  if self.root <= 1 then self.root = self:makenode(val, 1) return end
  local pos = self.root
  local added = false
  while not added do
    if self.lessthan(val, self.v[pos]) then
      if 1 < self.l[pos] then
        pos = self.l[pos]
      else
        self.l[pos] = self:makenode(val, pos)
        pos = self.l[pos]
        added = true
      end
    else
      if 1 < self.r[pos] then
        pos = self.r[pos]
      else
        self.r[pos] = self:makenode(val, pos)
        pos = self.r[pos]
        added = true
      end
    end
  end
  while 1 < pos do
    local child, parent = pos, self.p[pos]
    if parent <= 1 then
      break
    end
    self:recalcCount(parent)
    if self.l[parent] == child then
      if self.lc[parent] - 1 == self.rc[parent] then
        pos = parent
      elseif self.lc[parent] - 2 == self.rc[parent] then
        self:recalcCount(child)
        if self.lc[child] - 1 == self.rc[child] then
          self:rotR(child, parent)
        else
          local cr = self.r[child]
          self:rotL(cr, child)
          self:rotR(cr, parent)
        end
        pos = 1
      else
        self:recalcCountAll(child)
        pos = 1
      end
    else -- parent.r == child
      if self.rc[parent] - 1 == self.lc[parent] then
        pos = parent
      elseif self.rc[parent] - 2 == self.lc[parent] then
        self:recalcCount(child)
        if self.rc[child] - 1 == self.lc[child] then
          self:rotL(child, parent)
        else
          local cl = self.l[child]
          self:rotR(cl, child)
          self:rotL(cl, parent)
        end
        pos = 1
      else
        self:recalcCountAll(child)
        pos = 1
      end
    end
  end
end

AvlTree.rmsub = function(self, node)
  while 1 < node do
    self:recalcCount(node)
    if self.lc[node] == self.rc[node] then
      node = self.p[node]
    elseif self.lc[node] + 1 == self.rc[node] then
      self:recalcCountAll(self.p[node])
      node = 1
    else
      if self.lc[self.r[node]] == self.rc[self.r[node]] then
        self:rotL(self.r[node], node)
        node = 1
      elseif self.lc[self.r[node]] + 1 == self.rc[self.r[node]] then
        local nr = self.r[node]
        self:rotL(nr, node)
        node = nr
      else
        local nrl = self.l[self.r[node]]
        self:rotR(nrl, self.r[node])
        self:rotL(nrl, node)
        node = nrl
      end
    end
  end
end

AvlTree.pop = function(self)
  local node = self.root
  while 1 < self.l[node] do
    node = self.l[node]
  end
  local v = self.v[node]
  if 1 < self.p[node] then
    self.p[self.r[node]] = self.p[node]
    self.l[self.p[node]] = self.r[node]
    self:rmsub(self.p[node])
  else
    self.p[self.r[node]] = 1
    self.root = self.r[node]
  end
  table.insert(self.box, node)
  return v
end

AvlTree.new = function(lessthan, n)
    local obj = {}
    setmetatable(obj, {__index = AvlTree})
    obj:create(lessthan, n)
    return obj
end

local n, m = io.read("*n", "*n")
local ps, qs, cs = {}, {}, {}
local companies = {}
local stations = {}
for i = 1, n do
  stations[i] = {}
end
for i = 1, m do
  local p, q, c = io.read("*n", "*n", "*n")
  if not companies[c] then companies[c] = {} end
  if stations[p][c] and stations[q][c] then
    if stations[p][c] ~= stations[q][c] then
      local ci_p, ci_q = stations[p][c], stations[q][c]
      if #companies[c][ci_p] < #companies[c][ci_q] then
        for j = 1, #companies[c][ci_p] do
          local st = companies[c][ci_p][j]
          stations[st][c] = ci_q
          table.insert(companies[c][ci_q], st)
        end
        companies[c][ci_p] = {}
      else
        for j = 1, #companies[c][ci_q] do
          local st = companies[c][ci_q][j]
          stations[st][c] = ci_p
          table.insert(companies[c][ci_p], st)
        end
        companies[c][ci_q] = {}
      end
    end
  elseif not stations[p][c] and not stations[q][c] then
    table.insert(companies[c], {p, q})
    stations[p][c] = #companies[c]
    stations[q][c] = #companies[c]
  elseif stations[p][c] then
    local idx = stations[p][c]
    stations[q][c] = idx
    table.insert(companies[c][idx], q)
  else
    local idx = stations[q][c]
    stations[p][c] = idx
    table.insert(companies[c][idx], p)
  end
end
local len = {}
local asked = {}
local tasknum = 0
local done = 0
local tasktree = AvlTree.new(function(x, y) return len[x[1]][x[2]] < len[y[1]][y[2]] end, 200000)
for i = 1, n do
  asked[i] = false
  len[i] = {}
  for company, group in pairs(stations[i]) do
    len[i][company] = -1
  end
end
local function addtask(station, company)
  tasknum = tasknum + 1
  tasktree:add({station, company})
end
for company, group in pairs(stations[1]) do
  len[1][company] = 1
  addtask(1, company)
end
local e,f = 0,0
while done < tasknum do
  done = done + 1
  local taskidx = tasktree:pop()
  local src_station, src_company = taskidx[1], taskidx[2]
  local src_group = stations[src_station][src_company]
  local srclen = len[src_station][src_company]
  if not asked[src_station] then
    asked[src_station] = true
    for dst_company, _g in pairs(stations[src_station]) do
      if src_company ~= dst_company then
        local dstlen = len[src_station][dst_company]
        if dstlen == -1 or srclen + 1 < dstlen then
          len[src_station][dst_company] = srclen + 1
          addtask(src_station, dst_company)
        end
      end
    end
  end
  if 0 < #companies[src_company][src_group] then
    for i = 1, #companies[src_company][src_group] do
      local dst_station = companies[src_company][src_group][i]
      local dstlen = len[dst_station][src_company]
      if dstlen == -1 or srclen < dstlen then
        len[dst_station][src_company] = srclen
        addtask(dst_station, src_company)
      end
    end
    companies[src_company][src_group] = {}
  end
end
local ret = -1
local mmi = math.min
for company, group in pairs(stations[n]) do
  local dstlen = len[n][company]
  if 0 < dstlen then
    if ret == -1 then
      ret = dstlen
    else
      ret = mmi(ret, dstlen)
    end
  end
end
print(ret)

Score : 600 points

Problem Statement

Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.

The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This line is operated by company c_i.

You can change trains at a station where multiple lines are available.

The fare system used in this subway system is a bit strange. When a passenger only uses lines that are operated by the same company, the fare is 1 yen (the currency of Japan). Whenever a passenger changes to a line that is operated by a different company from the current line, the passenger is charged an additional fare of 1 yen. In a case where a passenger who changed from some company A's line to another company's line changes to company A's line again, the additional fare is incurred again.

Snuke is now at station 1 and wants to travel to station N by subway. Find the minimum required fare.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq 2×10^5

1 \leq p_i \leq N (1 \leq i \leq M)

1 \leq q_i \leq N (1 \leq i \leq M)

1 \leq c_i \leq 10^6 (1 \leq i \leq M)

p_i \neq q_i (1 \leq i \leq M)

Input

The input is given from Standard Input in the following format:

N M
p_1 q_1 c_1
:
p_M q_M c_M

Output

Print the minimum required fare. If it is impossible to get to station N by subway, print -1 instead.

Sample Input 1

3 3
1 2 1
2 3 1
3 1 2

Sample Output 1

1

Use company 1's lines: 1 → 2 → 3. The fare is 1 yen.

Sample Input 2

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

Sample Output 2

2

First, use company 1's lines: 1 → 3 → 2 → 5 → 6. Then, use company 5's lines: 6 → 7 → 8. The fare is 2 yen.

Sample Input 3

2 0

Sample Output 3

-1


local mma = math.max
local mfl, mce, mmi = math.floor, math.ceil, math.min
local SegForAvl = {}
local segavl_mergefunc = function(x, y)
  if x and y then return mmi(x, y)
  elseif x then return x
  elseif y then return y
  else return false end
end
SegForAvl.updateAll = function(self)
  for i = self.stagenum - 1, 1, -1 do
    for j = 1, self.cnt[i] do
      self.stage[i][j] = self.stage[i + 1][j * 2 - 1]
    end
  end
end
SegForAvl.create = function(self, n)
  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] = i end
  self:updateAll()
end
SegForAvl.hold = function(self)
  local idx = self.stage[1][1]
  local ridx = idx
  self.stage[self.stagenum][idx] = false
  for i = self.stagenum - 1, 1, -1 do
    local dst = mce(idx / 2)
    local rem = dst * 4 - 1 - idx
    self.stage[i][dst] = segavl_mergefunc(self.stage[i + 1][idx], self.stage[i + 1][rem])
    idx = dst
  end
  return ridx
end
SegForAvl.release = function(self, idx)
  self.stage[self.stagenum][idx] = idx
  for i = self.stagenum - 1, 1, -1 do
    local dst = mce(idx / 2)
    local rem = dst * 4 - 1 - idx
    self.stage[i][dst] = segavl_mergefunc(self.stage[i + 1][idx], self.stage[i + 1][rem])
    idx = dst
  end
end
SegForAvl.new = function(n)
  local obj = {}
  setmetatable(obj, {__index = SegForAvl})
  obj:create(n)
  return obj
end

local SegAvlTree = {}
SegAvlTree.makenode = function(self, val, parent)
  local i = self.seg:hold()
  self.v[i], self.u[i], self.p[i] = val, true, parent
  self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 0, 0
  return i
end
SegAvlTree.create = function(self, lessthan, n)
  self.lessthan = lessthan
  self.seg = SegForAvl.new(n)
  -- value, leftCount, rightCount, left, right, parent, used
  self.v, self.lc, self.rc, self.l, self.r, self.p, self.u = {}, {}, {}, {}, {}, {}, {}
  for i = 1, n do
    self.v[i], self.u[i], self.p[i] = 0, false, 0
    self.lc[i], self.rc[i], self.l[i], self.r[i] = 0, 0, 0, 0
  end
end

SegAvlTree.recalcCount = function(self, i)
  if self.u[i] then
    if self.u[self.l[i]] then self.lc[i] = 1 + mma(self.lc[self.l[i]], self.rc[self.l[i]])
    else self.lc[i] = 0
    end
    if self.u[self.r[i]] then self.rc[i] = 1 + mma(self.lc[self.r[i]], self.rc[self.r[i]])
    else self.rc[i] = 0
    end
  end
end
SegAvlTree.recalcCountAll = function(self, i)
  while self.u[i] do
    self:recalcCount(i)
    i = self.p[i]
  end
end

SegAvlTree.rotR = function(self, child, parent)
  local granp = self.p[parent]
  self.r[child], self.l[parent] = parent, self.r[child]
  self.p[child], self.p[parent] = granp, child
  if self.u[self.l[parent]] then self.p[self.l[parent]] = parent end
  if self.u[granp] then
    if self.l[granp] == parent then
      self.l[granp] = child
    else
      self.r[granp] = child
    end
  else
    self.root = child
  end
  self:recalcCountAll(parent)
end

SegAvlTree.rotL = function(self, child, parent)
  local granp = self.p[parent]
  self.l[child], self.r[parent] = parent, self.l[child]
  self.p[child], self.p[parent] = granp, child
  if self.u[self.r[parent]] then self.p[self.r[parent]] = parent end
  if self.u[granp] then
    if self.r[granp] == parent then
      self.r[granp] = child
    else
      self.l[granp] = child
    end
  else
    self.root = child
  end
  self:recalcCountAll(parent)
end

SegAvlTree.add = function(self, val)
  if not self.u[self.root] then self.root = self:makenode(val, 0) return end
  local pos = self.root
  local added = false
  while not added do
    if self.lessthan(val, self.v[pos]) then
      if self.u[self.l[pos]] then
        pos = self.l[pos]
      else
        self.l[pos] = self:makenode(val, pos)
        pos = self.l[pos]
        added = true
      end
    else
      if self.u[self.r[pos]] then
        pos = self.r[pos]
      else
        self.r[pos] = self:makenode(val, pos)
        pos = self.r[pos]
        added = true
      end
    end
  end
  while self.u[pos] do
    local child, parent = pos, self.p[pos]
    if not self.u[parent] then
      break
    end
    self:recalcCount(parent)
    if self.l[parent] == child then
      if self.lc[parent] - 1 == self.rc[parent] then
        pos = parent
      elseif self.lc[parent] - 2 == self.rc[parent] then
        self:recalcCount(child)
        if self.lc[child] - 1 == self.rc[child] then
          self:rotR(child, parent)
        else
          local cr = self.r[child]
          self:rotL(cr, child)
          self:rotR(cr, parent)
        end
        self:recalcCountAll(child)
        pos = nil
      else
        self:recalcCountAll(child)
        pos = nil
      end
    else -- parent.r == child
      if self.rc[parent] - 1 == self.lc[parent] then
        pos = parent
      elseif self.rc[parent] - 2 == self.lc[parent] then
        self:recalcCount(child)
        if self.rc[child] - 1 == self.lc[child] then
          self:rotL(child, parent)
        else
          local cl = self.l[child]
          self:rotR(cl, child)
          self:rotL(cl, parent)
        end
        self:recalcCountAll(child)
        pos = nil
      else
        self:recalcCountAll(child)
        pos = nil
      end
    end
  end
end

SegAvlTree.rmsub = function(self, node)
  while self.u[node] do
    self:recalcCount(node)
    if self.lc[node] == self.rc[node] then
      node = self.p[node]
    elseif self.lc[node] + 1 == self.rc[node] then
      self:recalcCountAll(self.p[node])
      node = nil
    else
      if self.lc[self.r[node]] == self.rc[self.r[node]] then
        self:rotL(self.r[node], node)
        self:recalcCountAll(node)
        node = nil
      elseif self.lc[self.r[node]] + 1 == self.rc[self.r[node]] then
        local nr = self.r[node]
        self:rotL(nr, node)
        node = nr
      else
        local nrl = self.l[self.r[node]]
        self:rotR(nrl, self.r[node])
        self:rotL(nrl, node)
        node = nrl
      end
    end
  end
end

SegAvlTree.pop = function(self)
  local node = self.root
  while self.u[self.l[node]] do
    node = self.l[node]
  end
  local v = self.v[node]
  if self.u[self.p[node]] then
    if self.u[self.r[node]] then self.p[self.r[node]] = self.p[node] end
    self.l[self.p[node]] = self.r[node]
    self:rmsub(self.p[node])
  else
    if self.r[node] then self.p[self.r[node]] = 0 end
    self.root = self.r[node]
  end
  self.seg:release(node)
  return v
end

SegAvlTree.new = function(lessthan, n)
    local obj = {}
    setmetatable(obj, {__index = SegAvlTree})
    obj:create(lessthan, n)
    return obj
end

local n, m = io.read("*n", "*n")
local ps, qs, cs = {}, {}, {}
local companies = {}
local stations = {}
for i = 1, n do
  stations[i] = {}
end
for i = 1, m do
  local p, q, c = io.read("*n", "*n", "*n")
  if not companies[c] then companies[c] = {} end
  if stations[p][c] and stations[q][c] then
    if stations[p][c] ~= stations[q][c] then
      local ci_p, ci_q = stations[p][c], stations[q][c]
      if #companies[c][ci_p] < #companies[c][ci_q] then
        for j = 1, #companies[c][ci_p] do
          local st = companies[c][ci_p][j]
          stations[st][c] = ci_q
          table.insert(companies[c][ci_q], st)
        end
        companies[c][ci_p] = {}
      else
        for j = 1, #companies[c][ci_q] do
          local st = companies[c][ci_q][j]
          stations[st][c] = ci_p
          table.insert(companies[c][ci_p], st)
        end
        companies[c][ci_q] = {}
      end
    end
  elseif not stations[p][c] and not stations[q][c] then
    table.insert(companies[c], {p, q})
    stations[p][c] = #companies[c]
    stations[q][c] = #companies[c]
  elseif stations[p][c] then
    local idx = stations[p][c]
    stations[q][c] = idx
    table.insert(companies[c][idx], q)
  else
    local idx = stations[q][c]
    stations[p][c] = idx
    table.insert(companies[c][idx], p)
  end
end
local len = {}
local asked = {}
local tasknum = 0
local done = 0
local tasktree = SegAvlTree.new(function(x, y) return len[x[1]][x[2]] < len[y[1]][y[2]] end, 200000)
for i = 1, n do
  asked[i] = false
  len[i] = {}
  for company, group in pairs(stations[i]) do
    len[i][company] = -1
  end
end
local function addtask(station, company)
  tasknum = tasknum + 1
  tasktree:add({station, company})
end
for company, group in pairs(stations[1]) do
  len[1][company] = 1
  addtask(1, company)
end
local e,f = 0,0
while done < tasknum do
  done = done + 1
  local taskidx = tasktree:pop()
  local src_station, src_company = taskidx[1], taskidx[2]
  local src_group = stations[src_station][src_company]
  local srclen = len[src_station][src_company]
  if not asked[src_station] then
    asked[src_station] = true
    for dst_company, _g in pairs(stations[src_station]) do
      if src_company ~= dst_company then
        local dstlen = len[src_station][dst_company]
        if dstlen == -1 or srclen + 1 < dstlen then
          len[src_station][dst_company] = srclen + 1
          addtask(src_station, dst_company)
        end
      end
    end
  end
  if 0 < #companies[src_company][src_group] then
    for i = 1, #companies[src_company][src_group] do
      local dst_station = companies[src_company][src_group][i]
      local dstlen = len[dst_station][src_company]
      if dstlen == -1 or srclen < dstlen then
        len[dst_station][src_company] = srclen
        addtask(dst_station, src_company)
      end
    end
    companies[src_company][src_group] = {}
  end
end
local ret = -1
local mmi = math.min
for company, group in pairs(stations[n]) do
  local dstlen = len[n][company]
  if 0 < dstlen then
    if ret == -1 then
      ret = dstlen
    else
      ret = mmi(ret, dstlen)
    end
  end
end
print(ret)


local n, m = io.read("*n", "*n")
local ps, qs, cs = {}, {}, {}
local companies = {}
local stations = {}
for i = 1, n do
  stations[i] = {}
end
for i = 1, m do
  local p, q, c = io.read("*n", "*n", "*n")
  if not companies[c] then companies[c] = {} end
  if stations[p][c] and stations[q][c] then
    if stations[p][c] ~= stations[q][c] then
      local ci_p, ci_q = stations[p][c], stations[q][c]
      if #companies[c][ci_p] < #companies[c][ci_q] then
        for j = 1, #companies[c][ci_p] do
          local st = companies[c][ci_p][j]
          stations[st][c] = ci_q
          table.insert(companies[c][ci_q], st)
        end
        companies[c][ci_p] = {}
      else
        for j = 1, #companies[c][ci_q] do
          local st = companies[c][ci_q][j]
          stations[st][c] = ci_p
          table.insert(companies[c][ci_p], st)
        end
        companies[c][ci_q] = {}
      end
    end
  elseif not stations[p][c] and not stations[q][c] then
    table.insert(companies[c], {p, q})
    stations[p][c] = #companies[c]
    stations[q][c] = #companies[c]
  elseif stations[p][c] then
    local idx = stations[p][c]
    stations[q][c] = idx
    table.insert(companies[c][idx], q)
  else
    local idx = stations[q][c]
    stations[p][c] = idx
    table.insert(companies[c][idx], p)
  end
end
local len = {}
local taskstate = {}
local tasks = {}
local asked = {}
local tasknum = 0
local done = 0
local tasklim = 200000
for i = 1, n do
  asked[i] = false
  len[i] = {}
  taskstate[i] = {}
  for company, group in pairs(stations[i]) do
    len[i][company] = -1
    taskstate[i][company] = false
  end
end
local function addtask(station, company)
  if not taskstate[station][company] then
    taskstate[station][company] = true
    tasknum = tasknum + 1
    local taskidx = tasknum % tasklim
    if taskidx == 0 then taskidx = tasklim end
    tasks[taskidx] = {station, company}
  end
end
for company, group in pairs(stations[1]) do
  len[1][company] = 1
  addtask(1, company)
end
local e,f = 0,0
while done < tasknum do
  done = done + 1
  local taskidx = done % tasklim
  if taskidx == 0 then taskidx = tasklim end
  local src_station, src_company = tasks[taskidx][1], tasks[taskidx][2]
  local src_group = stations[src_station][src_company]
  local srclen = len[src_station][src_company]
  taskstate[src_station][src_company] = false
  if not asked[src_station] then
    asked[src_station] = true
    for dst_company, _g in pairs(stations[src_station]) do
      if src_company ~= dst_company then
        local dstlen = len[src_station][dst_company]
        if dstlen == -1 or srclen + 1 < dstlen then
          len[src_station][dst_company] = srclen + 1
          addtask(src_station, dst_company)
        end
      end
    end
  end
  if 0 < #companies[src_company][src_group] then
    for i = 1, #companies[src_company][src_group] do
      local dst_station = companies[src_company][src_group][i]
      local dstlen = len[dst_station][src_company]
      if dstlen == -1 or srclen < dstlen then
        len[dst_station][src_company] = srclen
        addtask(dst_station, src_company)
      end
    end
    companies[src_company][src_group] = {}
  end
end
local ret = -1
local mmi = math.min
for company, group in pairs(stations[n]) do
  local dstlen = len[n][company]
  if 0 < dstlen then
    if ret == -1 then
      ret = dstlen
    else
      ret = mmi(ret, dstlen)
    end
  end
end
print(ret)


local n, m = io.read("*n", "*n")
local ps, qs, cs = {}, {}, {}
local companies = {}
local stations = {}
for i = 1, n do
  stations[i] = {}
end
for i = 1, m do
  local p, q, c = io.read("*n", "*n", "*n")
  if not companies[c] then companies[c] = {} end
  if stations[p][c] and stations[q][c] then
    if stations[p][c] ~= stations[q][c] then
      local ci_p, ci_q = stations[p][c], stations[q][c]
      if #companies[c][ci_p] < #companies[c][ci_q] then
        for j = 1, #companies[c][ci_p] do
          local st = companies[c][ci_p][j]
          stations[st][c] = ci_q
          table.insert(companies[c][ci_q], st)
        end
        companies[c][ci_p] = {}
      else
        for j = 1, #companies[c][ci_q] do
          local st = companies[c][ci_q][j]
          stations[st][c] = ci_p
          table.insert(companies[c][ci_p], st)
        end
        companies[c][ci_q] = {}
      end
    end
  elseif not stations[p][c] and not stations[q][c] then
    table.insert(companies[c], {p, q})
    stations[p][c] = #companies[c]
    stations[q][c] = #companies[c]
  elseif stations[p][c] then
    local idx = stations[p][c]
    stations[q][c] = idx
    table.insert(companies[c][idx], q)
  else
    local idx = stations[q][c]
    stations[p][c] = idx
    table.insert(companies[c][idx], p)
  end
end
local len = {}
local taskstate = {}
local tasks = {}
local tasknum = 0
local done = 0
local tasklim = 200000
local c_g_num = 0
local c_g_map = {}
local c_g_stations = {}
for company, groups in pairs(companies) do
  c_g_map[company] = {}
  for i = 1, #groups do
    c_g_num = c_g_num + 1
    c_g_map[company][i] = c_g_num
    len[c_g_num] = -1
    taskstate[c_g_num] = false
    c_g_stations[c_g_num] = groups[i]
  end
end
local function addtask(c_g_idx)
  if not taskstate[c_g_idx] then
    taskstate[c_g_idx] = true
    tasknum = tasknum + 1
    local taskidx = tasknum % tasklim
    if taskidx == 0 then taskidx = tasklim end
    tasks[taskidx] = c_g_idx
  end
end
for company, group in pairs(stations[1]) do
  local cgidx = c_g_map[company][group]
  len[cgidx] = 1
  addtask(cgidx)
end
local e = 0
while done < tasknum do
  done = done + 1
  local taskidx = done % tasklim
  if taskidx == 0 then taskidx = tasklim end
  local src_cg = tasks[taskidx]
  local srclen = len[src_cg]
  taskstate[src_cg] = false
  local tmptbl = {}
  for i = 1, #c_g_stations[src_cg] do
    local station = c_g_stations[src_cg][i]
    for dst_company, dst_group in pairs(stations[station]) do
      e = e + 1
      local dstcg = c_g_map[dst_company][dst_group]
      local dstlen = len[dstcg]
      if dstlen == -1 or srclen + 1 < dstlen then
        len[dstcg] = srclen + 1
        table.insert(tmptbl, dstcg)
        -- addtask(dst_company, dst_group)
      end
    end
  end
  table.sort(tmptbl, function(a, b) return len[a] < len[b] end)
  for i = 1, #tmptbl do
    addtask(tmptbl[i])
  end
end
local ret = -1
local mmi = math.min
for company, group in pairs(stations[n]) do
  local dstlen = len[c_g_map[company][group]]
  if 0 < dstlen then
    if ret == -1 then
      ret = dstlen
    else
      ret = mmi(ret, dstlen)
    end
  end
end
print(os.clock())
print(ret)


local mmi, mma = math.min, math.max
local n, x = io.read("*n", "*n")
local a = {}
local t = {}
for i = 1, n do
  a[i] = io.read("*n")
  t[i] = {a[i]}
end
for i = 1, n do
  for j = 1, n - 1 do
    local use = i - j
    if use <= 0 then use = use + n end
    t[i][j + 1] = mmi(t[i][j], a[use])
  end
end
local ret = 0
for i = 1, n do
  ret = ret + t[i][1]
end
for j = 2, n do
  local v = 0
  for i = 1, n do
    v = v + t[i][j]
  end
  ret = mmi(ret, x * (j - 1) + v)
end
print(ret)

Score : 400 points

Problem Statement

Snuke lives in another world, where slimes are real creatures and kept by some people.
Slimes come in N colors. Those colors are conveniently numbered 1 through N.
Snuke currently has no slime. His objective is to have slimes of all the colors together.

Snuke can perform the following two actions:

Select a color i (1≤i≤N), such that he does not currently have a slime in color i, and catch a slime in color i. This action takes him a_i seconds.

Cast a spell, which changes the color of all the slimes that he currently has. The color of a slime in color i (1≤i≤N-1) will become color i+1, and the color of a slime in color N will become color 1. This action takes him x seconds.

Find the minimum time that Snuke needs to have slimes in all N colors.

Constraints

2≤N≤2,000

a_i are integers.

1≤a_i≤10^9

x is an integer.

1≤x≤10^9

Input

The input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Find the minimum time that Snuke needs to have slimes in all N colors.

Sample Input 1

2 10
1 100

Sample Output 1

12

Snuke can act as follows:

Catch a slime in color 1. This takes 1 second.

Cast the spell. The color of the slime changes: 1 → 2. This takes 10 seconds.

Catch a slime in color 1. This takes 1 second.

Sample Input 2

3 10
100 1 100

Sample Output 2

23

Snuke can act as follows:

Catch a slime in color 2. This takes 1 second.

Cast the spell. The color of the slime changes: 2 → 3. This takes 10 seconds.

Catch a slime in color 2. This takes 1 second.

Cast the soell. The color of each slime changes: 3 → 1, 2 → 3. This takes 10 seconds.

Catch a slime in color 2. This takes 1 second.

Sample Input 3

4 10
1 2 3 4

Sample Output 3

10

Snuke can act as follows:

Catch a slime in color 1. This takes 1 second.

Catch a slime in color 2. This takes 2 seconds.

Catch a slime in color 3. This takes 3 seconds.

Catch a slime in color 4. This takes 4 seconds.


local mma = math.max
local n, k = io.read("*n", "*n")
local edge = {}
local len = {}
local childcnt = {}
local parent = {}
for i = 1, n do
  edge[i] = {}
  len[i] = -1
  childcnt[i] = 0
  parent[i] = 0
end
len[1] = 0
local ret = io.read("*n") == 1 and 0 or 1
for i = 2, n do
  local a = io.read("*n")
  table.insert(edge[a], i)
  table.insert(edge[i], a)
end
local tasks = {1}
for it = 1, n do
  local src = tasks[it]
  for i = 1, #edge[src] do
    local dst = edge[src][i]
    if len[dst] == -1 then
      len[dst] = len[src] + 1
      table.insert(tasks, dst)
      childcnt[src] = childcnt[src] + 1
      parent[dst] = src
    end
  end
end
local maxlen = {}
tasks = {}
for i = 1, n do
  maxlen[i] = len[i]
  if childcnt[i] == 0 then
    table.insert(tasks, i)
  end
end
for i = 1, n - 1 do
  local c = tasks[i]
  local p = parent[c]
  if k < maxlen[c] then
    if maxlen[c] - len[c] == k - 1 then
      ret = ret + 1
    else
      maxlen[p] = mma(maxlen[p], maxlen[c])
    end
  else
    maxlen[p] = mma(maxlen[p], maxlen[c])
  end
  childcnt[p] = childcnt[p] - 1
  if childcnt[p] == 0 then
    table.insert(tasks, p)
  end
end
print(ret)

Score : 800 points

Problem Statement

There are N towns in Snuke Kingdom, conveniently numbered 1 through N.
Town 1 is the capital.

Each town in the kingdom has a Teleporter, a facility that instantly transports a person to another place.
The destination of the Teleporter of town i is town a_i (1≤a_i≤N).
It is guaranteed that one can get to the capital from any town by using the Teleporters some number of times.

King Snuke loves the integer K.
The selfish king wants to change the destination of the Teleporters so that the following holds:

Starting from any town, one will be at the capital after using the Teleporters exactly K times in total.

Find the minimum number of the Teleporters whose destinations need to be changed in order to satisfy the king's desire.

Constraints

2≤N≤10^5

1≤a_i≤N

One can get to the capital from any town by using the Teleporters some number of times.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

N K
a_1 a_2 ... a_N

Output

Print the minimum number of the Teleporters whose destinations need to be changed in order to satisfy King Snuke's desire.

Sample Input 1

3 1
2 3 1

Sample Output 1

2

Change the destinations of the Teleporters to a = (1,1,1).

Sample Input 2

4 2
1 1 2 2

Sample Output 2

0

There is no need to change the destinations of the Teleporters, since the king's desire is already satisfied.

Sample Input 3

8 2
4 1 2 3 1 2 3 4

Sample Output 3

3

For example, change the destinations of the Teleporters to a = (1,1,2,1,1,2,2,4).


local n, k = io.read("*n", "*n")
local edge = {}
local len = {}
for i = 1, n do
  edge[i] = {}
  len[i] = -1
end
len[1] = 0
local ret = io.read("*n") == 1 and 0 or 1
for i = 2, n do
  local a = io.read("*n")
  table.insert(edge[a], i)
  table.insert(edge[i], a)
end
local tasks = {1}
for it = 1, n do
  local src = tasks[it]
  for i = 1, #edge[src] do
    local dst = edge[src][i]
    if len[dst] == -1 then
      len[dst] = len[src] + 1
      table.insert(tasks, dst)
    end
  end
end
-- reuse "tasks"
for i = 1, n do
  tasks[i] = i
end
table.sort(tasks, function(a, b) return len[a] < len[b] end)
local offset = 0
for i = 2, n do
  if len[tasks[i]] - offset == k + 1 then
    ret = ret + 1
    if i < n and k + 1 < len[tasks[i + 1]] - offset then
      offset = offset + k
    end
  end
end
print(ret)


local n, k = io.read("*n", "*n")
local edge = {}
local len = {}
for i = 1, n do
  edge[i] = {}
  len[i] = -1
end
len[1] = 0
local ret = io.read("*n") == 1 and 0 or 1
for i = 2, n do
  local a = io.read("*n")
  table.insert(edge[a], i)
  table.insert(edge[i], a)
end
local tasks = {1}
for it = 1, n do
  local src = tasks[it]
  for i = 1, #edge[src] do
    local dst = edge[src][i]
    if len[dst] == -1 then
      len[dst] = len[src] + 1
      table.insert(tasks, dst)
    end
  end
end
-- reuse "tasks"
for i = 1, n do
  tasks[i] = i
end
table.sort(tasks, function(a, b) return len[a] < len[b] end)
local offset = 0
for i = 2, n do
  if len[i] - offset == k + 1 then
    ret = ret + 1
    if i < n and k + 1 < len[i + 1] - offset then
      offset = offset + k
    end
  end
end
print(ret)


n,k,x,y=io.read("*n","*n","*n","*n")
if (k >= n) then
  print(n*x)
else
  print(k*x+(n-k)*y)
end

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

X yen (the currency of Japan) per night, for the first K nights

Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights.
Find his total accommodation fee.

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

N,\,K,\,X,\,Y are integers.

Input

The input is given from Standard Input in the following format:

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


n,k,x,y=io.read("*n","*n","*n","*n")
if (k >= n) then
  print(k*x)
else
  print(k*x+(n-k)*y)
end


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

local function getdivisorparts(x, primes)
  local prime_num = #primes
  local tmp = {}
  local lim = mce(msq(x))
  local primepos = 1
  local dv = primes[primepos]
  while primepos <= prime_num and dv <= lim do
    if x % dv == 0 then
      local asdf = {}
      asdf.p = dv
      asdf.cnt = 1
      x = x / dv
      while x % dv == 0 do
        x = x / dv
        asdf.cnt = asdf.cnt + 1
      end
      table.insert(tmp, asdf)
      lim = mce(msq(x))
    end
    if primepos == prime_num then break end
    primepos = primepos + 1
    dv = primes[primepos]
  end
  if x ~= 1 then
    local asdf = {}
    asdf.p, asdf.cnt = x, 1
    table.insert(tmp, asdf)
  end
  return tmp
end

local function getdivisor(divisorparts)
  local t = {}
  local pat = 1
  local len = #divisorparts
  local allpat = 1
  for i = 1, len do
    allpat = allpat * (1 + divisorparts[i].cnt)
  end
  for t_i_pat = 0, allpat - 1 do
    local div = allpat
    local i_pat = t_i_pat
    local ret = 1
    for i = 1, len do
      div = mfl(div / (divisorparts[i].cnt + 1))
      local mul = mfl(i_pat / div)
      i_pat = i_pat % div
      for j = 1, mul do
        ret = ret * divisorparts[i].p
      end
    end
    table.insert(t, ret)
  end
  table.sort(t)
  return t
end

local n, s = io.read("*n", "*n")
local lim = math.ceil(math.sqrt(n))

local function solve(x)
  local tn = n
  local c = 0
  while 0 < tn do
    c = c + tn % x
    tn = mfl(tn / x)
  end
  return c == s
end

local found = false
for x = 2, lim - 1 do
  if solve(x) then
    found = true
    print(x)
    break
  end
end
if not found then
  if n == s then
    print(n + 1)
    found = true
  elseif s < n then
    local mul = n - s
    local primes = getprimes(lim)
    local divp = getdivisorparts(mul, primes)
    local divs = getdivisor(divp)
    for i = 1, #divs do
      local cand = divs[i]
      local a1 = mfl(mul / cand)
      if a1 <= cand then
        local a0 = s - a1
        if 0 <= a0 and a0 <= cand then
          found = true
          print(cand + 1)
          break
        end
      end
    end
  end
  if not found then
    print(-1)
  end
end

Score : 500 points

Problem Statement

For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:

f(b,n) = n, when n < b

f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b

Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.

Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:

f(10,\,87654)=8+7+6+5+4=30

f(100,\,87654)=8+76+54=138

You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

Constraints

1 \leq n \leq 10^{11}

1 \leq s \leq 10^{11}

n,\,s are integers.

Input

The input is given from Standard Input in the following format:

n
s

Output

If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-1


s=io.read()
t={}
for i=1,#s do
    table.insert(t,s:sub(i,i))
end
table.sort(t)
x=table.concat(t,"")
if string.match(x,"E+N+S+W+") or string.match(x,"E+W+")==x or string.match(x,"N+S+")==x then
    print("Yes")
else
    print("No")
end

Score : 200 points

Problem Statement

Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip.
At the beginning of Day 1, he is at home. His plan is described in a string S of length N.
On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction:

North if the i-th letter of S is N

West if the i-th letter of S is W

South if the i-th letter of S is S

East if the i-th letter of S is E

He has not decided each day's travel distance. Determine whether it is possible to set each day's travel distance so that he will be back at home at the end of Day N.

Constraints

1 ≦ | S | ≦ 1000

S consists of the letters N, W, S, E.

Input

The input is given from Standard Input in the following format:

S

Output

Print Yes if it is possible to set each day's travel distance so that he will be back at home at the end of Day N. Otherwise, print No.

Sample Input 1

SENW

Sample Output 1

Yes

If Snuke travels a distance of 1 on each day, he will be back at home at the end of day 4.

Sample Input 2

NSNNSNSN

Sample Output 2

Yes

Sample Input 3

NNEW

Sample Output 3

No

Sample Input 4

W

Sample Output 4

No


s=io.read()
t={}
for i=1,#s do
    t[s:sub(i,i)]=1
end

counter=0
for _,v in pairs(t) do
    counter=counter+v
end
if counter%2==0 then
    print("Yes")
else
    print("No")
end


s=io.read()
t={}
for i=1,#s do
    t[s:sub(i,i)]=1
end

counter=0
for _,v in pairs(t) do
    counter=counter+v
end
print(counter)


local s = io.read()
local t = {}
t["N"] = 0
t["W"] = 0
t["S"] = 0
t["E"] = 0
for i = 1, #s do
  sstr = s:sub(i, i)
  t[sstr] = t[sstr] + 1
end
local ok = true
if 0 < t.N and 0 == t.S then
  ok = false
end
if 0 < t.S and 0 == t.N then
  ok = false
end
if 0 < t.W and 0 == t.E then
  ok = false
end
if 0 < t.E and 0 == t.W then
  ok = false
end
print(ok and "Yes" or "No")


local n = io.read("*n")
local a = {}
for i = 1, n do
  local tmp = {i, io.read("*n")}
  a[i] = tmp
end
table.sort(a, function(x, y) return x[2] < y[2] end)
local cnt = 0
for i = 1, n do
  if (i + a[i][1]) % 2 == 1 then
    cnt = cnt + 1
  end
end
print(cnt / 2)

Score : 600 points

Problem Statement

Snuke got an integer sequence of length N from his mother, as a birthday present. The i-th (1 ≦ i ≦ N) element of the sequence is a_i. The elements are pairwise distinct.
He is sorting this sequence in increasing order.
With supernatural power, he can perform the following two operations on the sequence in any order:

Operation 1: choose 2 consecutive elements, then reverse the order of those elements.

Operation 2: choose 3 consecutive elements, then reverse the order of those elements.

Snuke likes Operation 2, but not Operation 1. Find the minimum number of Operation 1 that he has to perform in order to sort the sequence in increasing order.

Constraints

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9

If i ≠ j, then A_i ≠ A_j.

All input values are integers.

Input

The input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the minimum number of times Operation 1 that Snuke has to perform.

Sample Input 1

4
2
4
3
1

Sample Output 1

1

The given sequence can be sorted as follows:

First, reverse the order of the last three elements. The sequence is now: 2,1,3,4.

Then, reverse the order of the first two elements. The sequence is now: 1,2,3,4.

In this sequence of operations, Operation 1 is performed once. It is not possible to sort the sequence with less number of Operation 1, thus the answer is 1.

Sample Input 2

5
10
8
5
3
2

Sample Output 2

0


Score : 100 points

Problem Statement

There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?

Constraints

1≦N≦100

Input

The input is given from Standard Input in the following format:

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from 1 to 10 is 55.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is 1 in this case.


local n = io.read("*n")
print(string.format("%d", n * (n + 1) / 2))


local s = io.read()
local n = #s
local t = {}
for i = 1, n do
  local ss = s:sub(i, i)
  if ss == "B" then
    if 0 < #t then table.remove(t) end
  else
    table.insert(t, ss)
  end
end
print(table.concat(t))

Score : 200 points

Problem Statement

Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.

To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:

The 0 key: a letter 0 will be inserted to the right of the string.

The 1 key: a letter 1 will be inserted to the right of the string.

The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.

Sig has launched the editor, and pressed these keys several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter 0 stands for the 0 key, the letter 1 stands for the 1 key and the letter B stands for the backspace key. What string is displayed in the editor now?

Constraints

1 ≦ |s| ≦ 10 (|s| denotes the length of s)

s consists of the letters 0, 1 and B.

The correct answer is not an empty string.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string displayed in the editor in the end.

Sample Input 1

01B0

Sample Output 1

00

Each time the key is pressed, the string in the editor will change as follows: 0, 01, 0, 00.

Sample Input 2

0BB1

Sample Output 2

1

Each time the key is pressed, the string in the editor will change as follows: 0, (empty), (empty), 1.


local s = io.read()
local v = {}
for i=1,#s do
  local c = s:sub(i,i)
  if c ~= 'B' then
    table.insert(v, c)
  else
    table.remove(v)
  end
end
print(table.concat(v,""))


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 N, L = read.nn()
local A = read.N(N)

local max = 0
local max_i = 0
for i=1,N-1 do
    local cur = A[i] + A[i+1]
    if cur > max then
        max = cur
        max_i = i
    end
end
if max < L then
    print("Impossible")
    return
else
    print("Possible")
    for i=1,N-1 do
        if i ~= max_i then
            print(i)
        end
    end
    print(max_i)
end

Problem Statement

We have N pieces of ropes, numbered 1 through N. The length of piece i is a_i.

At first, for each i (1≤i≤N-1), piece i and piece i+1 are tied at the ends, forming one long rope with N-1 knots. Snuke will try to untie all of the knots by performing the following operation repeatedly:

Choose a (connected) rope with a total length of at least L, then untie one of its knots.

Is it possible to untie all of the N-1 knots by properly applying this operation? If the answer is positive, find one possible order to untie the knots.

Constraints

2≤N≤10^5

1≤L≤10^9

1≤a_i≤10^9

All input values are integers.

Input

The input is given from Standard Input in the following format:

N L
a_1 a_2 ... a_n

Output

If it is not possible to untie all of the N-1 knots, print Impossible.

If it is possible to untie all of the knots, print Possible, then print another N-1 lines that describe a possible order to untie the knots. The j-th of those N-1 lines should contain the index of the knot that is untied in the j-th operation. Here, the index of the knot connecting piece i and piece i+1 is i.

If there is more than one solution, output any.

Sample Input 1

3 50
30 20 10

Sample Output 1

Possible
2
1

If the knot 1 is untied first, the knot 2 will become impossible to untie.

Sample Input 2

2 21
10 10

Sample Output 2

Impossible

Sample Input 3

5 50
10 20 30 40 50

Sample Output 3

Possible
1
2
3
4

Another example of a possible solution is 3, 4, 1, 2.


a,b,c = io.read("*n","*n","*n")
print(a*b*c==175 and "YES" or "NO")

Score : 100 points

Problem Statement

Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.

Constraints

1≦A,B,C≦10

Input

The input is given from Standard Input in the following format:

A B C

Output

If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.

Sample Input 1

5 5 7

Sample Output 1

YES

Using three phrases of length 5, 5 and 7, it is possible to construct a Haiku.

Sample Input 2

7 7 5

Sample Output 2

NO


x=0
y=0
for i in io.read():gmatch("%d+") do
  if i*1==5 then
    x=x+1
  elseif i*1==7 then
    y=y+1
  end
end
print((x==2 and y==1)and "YES"or "NO")


x=0
y=0
for i in io.read():gmatch("%d+") do
  if i==5 then
    x=x+1
  elseif i==7 then
    y=y+1
  end
end
print((x==2 and y==1)and "YES"or "NO")


local n,k=io.read("n","n")
local d={}
for i=1,k do
    d[io.read("n")]=true
end
for i=n,10*n do
    local copi=i
    local checker=true
    while copi>0 do
        if d[copi%10] then
            checker=false
            break
        end
        copi=copi//10
    end
    if checker then
        print(i)
        return
    end
end

Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

The input is given from Standard Input in the following format:

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999


n, k = io.read("*n", "*n")
ds = {}
for i = 1, k do ds[io.read("*n")] = true end
digits = {}
while(0 < n) do
    a = n % 10
    table.insert(digits, a)
    n = math.floor(n / 10)
end
len = #digits
for i = 1, len do
    val = digits[i]
    isok = (ds[val % 10] == nil)
    while(not isok)do
        val = val + 1
        isok = (ds[val % 10] == nil)
    end
    if(10 <= val) then
        val = val - 10
        if(i ~= len) then digits[i + 1] = digits[i + 1] + 1 else digits[i + 1] = 1 end
    end
    digits[i] = val
end
if(digits[len + 1] ~= nil) then
    val = digits[len + 1]
    isok = (ds[val] == nil)
    while(not isok) do
        val = val + 1
        isok = (ds[val] == nil)
    end
    digits[len + 1] = val
end
len = #digits
for i = len , 1, -1 do
    io.write(digits[i])
end
io.write("\n")