750_D. New Year and Fireworks

One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on.

Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t1, t2, ..., tn. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2n - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time — it is allowed and such parts do not crash.

Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells?

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 30) — the total depth of the recursion.

The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 5). On the i-th level each of 2i - 1 parts will cover ti cells before exploding.

Output

Print one integer, denoting the number of cells which will be visited at least once by any part of the firework.

Examples

Input

4
4 2 2 3

Output

39

Input

6
1 1 1 1 1 3

Output

85

Input

1
3

Output

3

Note

For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39.

<image>

For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level.

<image>

```python
import sys

plane = set()
crackers = {((0, -1), (0, 1))}

n = int(input())
a = [int(x) for x in input().split()]

crack_dict = {
    (1, 0): ((1, -1), (1, 1)),
    (1, 1): ((1, 0), (0, 1)),
    (0, 1): ((1, 1), (-1, 1)),
    (-1, 1): ((0, 1), (-1, 0)),
    (-1, 0): ((-1, 1), (-1, -1)),
    (-1, -1): ((-1, 0), (0, -1)),
    (0, -1): ((-1, -1), (1, -1)),
    (1, -1): ((0, -1), (1, 0)),
}

def move(cracker):
    point, direc = cracker
    point2 = (point[0] + direc[0], point[1] + direc[1])
    return (point2, direc)

def crack(cracker):
    point, direc = cracker
    direc1, direc2 = crack_dict[direc]
    return ((point, direc1), (point, direc2))

for x in a:
    for i in range(x):
        crackers = set((move(cracker) for cracker in crackers))
        plane.update((cracker[0] for cracker in crackers))
        # print(plane, file=sys.stderr)
    new_crackers = set()
    for cracker in crackers:
        new_crackers.update(crack(cracker))
    crackers = new_crackers

print(len(plane))

```


774_B. Significant Cups

Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters — its significance ci and width wi.

Stepan decided to expose some of his cups on a shelf with width d in such a way, that:

  * there is at least one Physics cup and at least one Informatics cup on the shelf,
  * the total width of the exposed cups does not exceed d,
  * from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too).

Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups.

Input

The first line contains three integers n, m and d (1 ≤ n, m ≤ 100 000, 1 ≤ d ≤ 109) — the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf.

Each of the following n lines contains two integers ci and wi (1 ≤ ci, wi ≤ 109) — significance and width of the i-th cup for Physics olympiads.

Each of the following m lines contains two integers cj and wj (1 ≤ cj, wj ≤ 109) — significance and width of the j-th cup for Informatics olympiads.

Output

Print the maximum possible total significance, which Stepan can get exposing cups on the shelf with width d, considering all the rules described in the statement.

If there is no way to expose cups on the shelf, then print 0.

Examples

Input

3 1 8
4 2
5 5
4 2
3 2

Output

8

Input

4 3 12
3 4
2 4
3 5
3 4
3 5
5 2
3 4

Output

11

Input

2 2 2
5 3
6 3
4 2
8 1

Output

0

Note

In the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8.

```python
n, m, d = map(int, input().split())
ph = [[int(j) for j in input().split()] for i in range(n)]
inf = [[int(j) for j in input().split()] for i in range(m)]
for i in range(n):
    ph[i][1] = -ph[i][1]
for i in range(m):
    inf[i][1] = -inf[i][1]
ph.sort(reverse=True)
inf.sort(reverse=True)
sw, sc = 0, 0
for p in inf:
    sc += p[0]
    d += p[1]
ans = 0
z = m - 1
for p in ph:
    sc += p[0]
    d += p[1]
    #print(sc, d)
    while z > 0 and d < 0:
        sc -= inf[z][0]
        d -= inf[z][1]
        z -= 1
    #print(sc, d)
    if d >= 0:
        ans = max(ans, sc)
print(ans)
```


799_B. T-shirt buying

A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3.

m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj.

A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served.

You are to compute the prices each buyer will pay for t-shirts.

Input

The first line contains single integer n (1 ≤ n ≤ 200 000) — the number of t-shirts.

The following line contains sequence of integers p1, p2, ..., pn (1 ≤ pi ≤ 1 000 000 000), where pi equals to the price of the i-th t-shirt.

The following line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3), where ai equals to the front color of the i-th t-shirt.

The following line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 3), where bi equals to the back color of the i-th t-shirt.

The next line contains single integer m (1 ≤ m ≤ 200 000) — the number of buyers.

The following line contains sequence c1, c2, ..., cm (1 ≤ cj ≤ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served.

Output

Print to the first line m integers — the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1.

Examples

Input

5
300 200 400 500 911
1 2 1 2 3
2 1 3 2 1
6
2 3 1 2 1 1

Output

200 400 300 500 911 -1

Input

2
1000000000 1
1 1
1 2
2
2 1

Output

1 1000000000

```python
n = int(input())
p = map(int,input().split())
a = map(int,input().split())
b = map(int,input().split())
m = int(input())
pos = map(int,input().split())

fut = zip(p,a,b)
fut=list(fut)
def sravni(elem):
    return elem[0]
fut.sort(key=sravni)

vz = []
for i in range(n):
    vz.append(False)

lastc = [0,0,0]
result = ""
for poset in pos:
    ctoim=-1
    for i in range(lastc[poset-1],n):
        if vz[i] == False:
            if fut[i][1] == poset or fut[i][2] ==poset:
                vz[i] = True
                ctoim = fut[i][0]
                lastc[poset - 1] = i+1
                break
    if ctoim == -1:
        lastc[poset-1] = n+1
    result+=str(ctoim)+" "
print(result)

```


819_B. Mister B and PR Shifts

Some time ago Mister B detected a strange signal from the space, which he started to study.

After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation.

Let's define the deviation of a permutation p as <image>.

Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them.

Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example:

  * k = 0: shift p1, p2, ... pn,
  * k = 1: shift pn, p1, ... pn - 1,
  * ...,
  * k = n - 1: shift p2, p3, ... pn, p1.

Input

First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation.

The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct.

Output

Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them.

Examples

Input

3
1 2 3

Output

0 0

Input

3
2 3 1

Output

0 1

Input

3
3 2 1

Output

2 1

Note

In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well.

In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift.

In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts.

```python
def main():
	n = int(input())
	data = input().split()

	#print(str(n) + " " + str(data))

	data = list(map(lambda x: int(x), data))
	res = 0
	ires = 0
	neg = 0
	when = [0] * n

	for i in range(n):
		data[i] = i + 1 - data[i]
		res += abs(data[i])
		if data[i] <= 0:
			neg += 1
		a = -data[i]
		if a < 0:
			a = a + n
		when[a] += 1
	#print(when)

	ares = res
	#print(str(res) + " " + str(ires) + " " + str(neg))
	for i in range(n):
		neg -= when[i]
		ares -= neg
		ares += (n - neg)
		x = data[n - i - 1] + i + 1
		ares -= x
		ares += n - x
		#print(str(res) + " " + str(ires) + " " + str(ares) + " " + str(i) + " " + str(neg))
		neg += 1
		if ares < res:
			res = ares
			ires = i + 1

	print(str(res) + " " + str(ires))

main()

```


865_B. Ordering Pizza

It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.

It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?

Input

The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow.

The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.

Output

Print the maximum total happiness that can be achieved.

Examples

Input

3 12
3 5 7
4 6 7
5 9 5

Output

84

Input

6 10
7 4 7
5 8 8
12 5 8
6 11 6
3 3 7
5 9 6

Output

314

Note

In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74.

```python
def solve(ls):

    ls.sort(key=lambda q: q[1] - q[0])

    m = sum(si for a, b, si in ls)

    k = s * (m // s)

    n = m - k

    x = y = z = 0

    for a, b, si in ls:

        if k >= si:

            k -= si

            z += si * a

        elif k:

            z += k * a

            x = (si - k) * a

            y = (si - k) * b

            k = 0

        else:

            x += si * a

            y += si * b

    return x, y, z, n

n,s = map(int,input().split())

first=[]

second=[]

for i in range(n):

	si, ai, bi = map(int,input().split())

	if ai>bi:

		first.append((ai,bi,si))

	else:

		second.append((bi,ai,si))

x1,y1,z1,n1 = solve(first)

x2,y2,z2,n2 = solve(second)

d = x1+x2 if n1+n2>s else max(x1+y2,x2+y1)

print(z1+z2+d)

# Made By Mostafa_Khaled
```


891_B. Gluttony

You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e.

<image>

Input

The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array.

The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the elements of the array.

Output

If there is no such array b, print -1.

Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a.

If there are multiple answers, print any of them.

Examples

Input

2
1 2

Output

2 1

Input

4
1000 100 10 1

Output

100 1 1000 10

Note

An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x.

Note that the empty subset and the subset containing all indices are not counted.

```python
import sys
input()
a = list(map(int, input().split()))
b = sorted(a)
for i in a:
	sys.stdout.write(str(b[b.index(i)-1]))
	sys.stdout.write(" ")
sys.stdout.write("\n")
```


913_E. Logical Expression

You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:

  * Operation AND ('&', ASCII code 38)
  * Operation OR ('|', ASCII code 124)
  * Operation NOT ('!', ASCII code 33)
  * Variables x, y and z (ASCII codes 120-122)
  * Parentheses ('(', ASCII code 40, and ')', ASCII code 41)

If more than one expression of minimum length exists, you should find the lexicographically smallest one.

Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:

E ::= E '|' T | T

T ::= T '&' F | F

F ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'

Input

The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000).

The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of <image>, <image> and <image>.

Output

You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.

Example

Input

4
00110011
00000111
11110000
00011111

Output

y
(y|z)&x
!x
x|y&z

Note

The truth table for the second function:

<image>


935_E. Fafa and Ancient Mathematics

Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression.

An Ahmes arithmetic expression can be defined as:

  * "d" is an Ahmes arithmetic expression, where d is a one-digit positive integer;
  * "(E1 op E2)" is an Ahmes arithmetic expression, where E1 and E2 are valid Ahmes arithmetic expressions (without spaces) and op is either plus ( + ) or minus ( - ).

For example 5, (1-1) and ((1+(2-3))-5) are valid Ahmes arithmetic expressions.

On his trip to Egypt, Fafa found a piece of papyrus paper having one of these Ahmes arithmetic expressions written on it. Being very ancient, the papyrus piece was very worn out. As a result, all the operators were erased, keeping only the numbers and the brackets. Since Fafa loves mathematics, he decided to challenge himself with the following task:

Given the number of plus and minus operators in the original expression, find out the maximum possible value for the expression on the papyrus paper after putting the plus and minus operators in the place of the original erased operators.

Input

The first line contains a string E (1 ≤ |E| ≤ 104) — a valid Ahmes arithmetic expression. All operators are erased and replaced with '?'.

The second line contains two space-separated integers P and M (0 ≤ min(P, M) ≤ 100) — the number of plus and minus operators, respectively.

It is guaranteed that P + M =  the number of erased operators.

Output

Print one line containing the answer to the problem.

Examples

Input

(1?1)
1 0

Output

2

Input

(2?(1?2))
1 1

Output

1

Input

((1?(5?7))?((6?2)?7))
3 2

Output

18

Input

((1?(5?7))?((6?2)?7))
2 3

Output

16

Note

  * The first sample will be (1 + 1) = 2.
  * The second sample will be (2 + (1 - 2)) = 1.
  * The third sample will be ((1 - (5 - 7)) + ((6 + 2) + 7)) = 18.
  * The fourth sample will be ((1 + (5 + 7)) - ((6 - 2) - 7)) = 16.

```python
from math import inf

class Node:
    def __init__(self, parent = None, leftExp = None, rightExp = None, signQ = 0):
        self.parent, self.leftExp, self.rightExp, self.signQ = parent, leftExp, rightExp, signQ
    def __str__(self):
        return "Node"

memo = {}

def Memoize(node, p, maxValue, minValue):
    if not node in memo:
        memo.update({node : {p : [maxValue, minValue]} })
    else:
        memo[node].update({p : [maxValue, minValue]})

def ExpMaxValue(root: Node, p):

    m = root.signQ - p
    """if root.signQ == 1:
        if p == 1:
            return [root.leftExp.value + root.rightExp.value, root.leftExp.value + root.rightExp.value]
        else:
            return [root.leftExp.value - root.rightExp.value, root.leftExp.value - root.rightExp.value]"""

    if root.signQ == 0:
        return [root.value, root.value]

    if root in memo:
        if p in memo[root]:
            return memo[root][p]

    if m == 0:
        value = ExpMaxValue(root.leftExp, root.leftExp.signQ)[0] + ExpMaxValue(root.rightExp, root.rightExp.signQ)[0]
        Memoize(root, p, value, value)
        return [value, value]
    if p == 0:
        value = ExpMaxValue(root.leftExp, 0)[0] - ExpMaxValue(root.rightExp, 0)[0]
        Memoize(root, p, value, value)
        return [value, value]

    maxValue = -inf
    minValue = inf
    if m >= p:
        for pQMid in range(2):
            pQLeftMin = min(p - pQMid, root.leftExp.signQ)
            for pQLeft in range(pQLeftMin + 1):
                if root.leftExp.signQ - pQLeft + (1 - pQMid) > m:
                    continue

                resLeft = ExpMaxValue(root.leftExp, pQLeft)
                resRight = ExpMaxValue(root.rightExp, p - pQMid - pQLeft)

                if pQMid == 1:
                    maxValue = max(resLeft[0] + resRight[0], maxValue)
                    minValue = min(resLeft[1] + resRight[1], minValue)
                else:
                    maxValue = max(resLeft[0] - resRight[1], maxValue)
                    minValue = min(resLeft[1] - resRight[0], minValue)
    else:
        for mQMid in range(2):
            mQLeftMin = min(m - mQMid, root.leftExp.signQ)
            for mQLeft in range(mQLeftMin + 1):
                pQLeft = root.leftExp.signQ - mQLeft
                if pQLeft + (1 - mQMid) > p:
                    continue

                resLeft = ExpMaxValue(root.leftExp, pQLeft)
                resRight = ExpMaxValue(root.rightExp, p - (1 - mQMid) - pQLeft)

                if mQMid == 0:
                    maxValue = max(resLeft[0] + resRight[0], maxValue)
                    minValue = min(resLeft[1] + resRight[1], minValue)
                else:
                    maxValue = max(resLeft[0] - resRight[1], maxValue)
                    minValue = min(resLeft[1] - resRight[0], minValue)

    Memoize(root, p, int(maxValue), int(minValue))

    return [int(maxValue), int(minValue)]

def PrintNodes(root: Node):
    if root.signQ != 0:
        leftExp = root.leftExp if root.leftExp.signQ != 0 else root.leftExp.value
        rightExp = root.rightExp if root.rightExp.signQ != 0 else root.rightExp.value
        check = root.signQ == root.leftExp.signQ + root.rightExp.signQ + 1
        print(root.signQ, root.parent, leftExp, rightExp, check)
        PrintNodes(root.leftExp)
        PrintNodes(root.rightExp)

def main():
    exp = str(input())
    if len(exp) == 1:
        print(exp)
        return

    #root = Node(None, None, None)
    #root.parent = root
    cNode = Node()
    isRight = False

    for i in range(1, len(exp) - 1):
        if exp[i] == '(':
            if not isRight:
                cNode.leftExp = Node(cNode)
                cNode = cNode.leftExp
            else:
                cNode.rightExp = Node(cNode)
                cNode = cNode.rightExp
            isRight = False
        elif exp[i] == '?':
            isRight = True
            cNode.signQ += 1
        elif exp[i] == ')':
            if cNode.parent != None:
                cNode.parent.signQ += cNode.signQ
            cNode = cNode.parent
            isRight = False
        else:
            if not isRight:
                cNode.leftExp = Node(cNode)
                cNode.leftExp.value = int(exp[i])
            else:
                cNode.rightExp = Node(cNode)
                cNode.rightExp.value = int(exp[i])

    #PrintNodes(cNode)

    ss = str(input()).split()
    p, m = int(ss[0]), int(ss[1])

    print(ExpMaxValue(cNode, p)[0])

main()
```


961_D. Pair Of Lines

You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct.

You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?

Input

The first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given.

Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct.

Output

If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO.

Examples

Input

5
0 0
0 1
1 1
1 -1
2 2

Output

YES

Input

5
0 0
1 0
2 1
1 1
2 3

Output

NO

Note

In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points.

<image>

```python
n = int(input())

lst = []
for x in range(n):
    (a, b) = map(int, input().split())
    lst.append((a, b))

def scal(x1, y1, x2, y2, x3, y3):
    if (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1) == 0:
        return True
    return False

def check():
    for x in range(n - 2):
        if len(s2) >= 3:
            if not scal(lst[s2[-3]][0], lst[s2[-3]][1], lst[s2[-2]][0], lst[s2[-2]][1], lst[s2[-1]][0], lst[s2[-1]][1]):
                return False
        if scal(lst[0][0], lst[0][1], lst[1][0], lst[1][1], lst[x + 2][0], lst[x + 2][1]):
            s1.append(x + 2)
        else:
            s2.append(x + 2)
    if len(s2) >= 3:
        if not scal(lst[s2[-3]][0], lst[s2[-3]][1], lst[s2[-2]][0], lst[s2[-2]][1], lst[s2[-1]][0], lst[s2[-1]][1]):
            return False
    return True

flag = True

if n >= 5:
    s1 = []
    s2 = []
    if not check():
        lst[1], lst[s2[0]] = lst[s2[0]], lst[1]
        x = s2[0]
        s1 = []
        s2 = []
        if not check():
            lst[0], lst[s2[0]] = lst[s2[0]], lst[0]
            s1 = []
            s2 = []
            if not check():
                flag = False

if flag:
    print("YES")
else:
    print("NO")

```


989_C. A Mist of Florescence

As the boat drifts down the river, a wood full of blossoms shows up on the riverfront.

"I've been here once," Mino exclaims with delight, "it's breathtakingly amazing."

"What is it like?"

"Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?"

There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses.

The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers.

According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers.

You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem.

Note that you can choose arbitrary n and m under the constraints below, they are not given in the input.

Input

The first and only line of input contains four space-separated integers a, b, c and d (1 ≤ a, b, c, d ≤ 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively.

Output

In the first line, output two space-separated integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns in the grid respectively.

Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively.

In case there are multiple solutions, print any. You can output each letter in either case (upper or lower).

Examples

Input

5 3 2 1

Output

4 7
DDDDDDD
DABACAD
DBABACD
DDDDDDD

Input

50 50 1 1

Output

4 50
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
ABABABABABABABABABABABABABABABABABABABABABABABABAB
BABABABABABABABABABABABABABABABABABABABABABABABABA
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD

Input

1 6 4 5

Output

7 7
DDDDDDD
DDDBDBD
DDCDCDD
DBDADBD
DDCDCDD
DBDBDDD
DDDDDDD

Note

In the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one.

<image>

```python
import sys
A, B, C, D = map(int, sys.stdin.readline().split())
cols = 49
rows = 50
res = [['.' for i in range(cols)] for j in range (rows)]
A -= 1
B -= 1
for r in range (rows // 2):
  for c in range (cols):
    if r % 2 == 0 or c % 2 == 0:
      res[r][c] = 'A'
    elif B > 0:
      res[r][c] = 'B'
      B -= 1
    elif C > 0:
      res[r][c] = 'C'
      C -= 1
    elif D > 0:
      res[r][c] = 'D'
      D -= 1
    else:
      res[r][c] = 'A'
for r in range (rows // 2, rows):
  for c in range (cols):
    if r % 2 == 1 or c % 2 == 0:
      res[r][c] = 'B'
    elif A > 0:
      res[r][c] = 'A'
      A -= 1
    elif C > 0:
      res[r][c] = 'C'
      C -= 1
    elif D > 0:
      res[r][c] = 'D'
      D -= 1
    else:
      res[r][c] = 'B'
print (rows, cols)
print('\n'.join(''.join (r) for r in res))

```


p02601 M-SOLUTIONS Programming Contest 2020 - Magic 2

M-kun has the following three cards:

* A red card with the integer A.
* A green card with the integer B.
* A blue card with the integer C.

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

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

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

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

Determine whether the magic can be successful.

Constraints

* 1 \leq A, B, C \leq 7
* 1 \leq K \leq 7
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C
K

Output

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

Examples

Input

7 2 5
3

Output

Yes

Input

7 4 2
3

Output

No

```python
a,b,c,k=map(int,open(0).read().split())
for i in' '*k:
 if a>=b:b*=2
 elif b>=c:c*=2
print('NYoe s'[a<b<c::2])
```


p02732 AtCoder Beginner Contest 159 - Banned K

We have N balls. The i-th ball has an integer A_i written on it.
For each k=1, 2, ..., N, solve the following problem and print the answer.

* Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

* 3 \leq N \leq 2 \times 10^5
* 1 \leq A_i \leq N
* 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

For each k=1,2,...,N, print a line containing the answer.

Examples

Input

5
1 1 2 1 2

Output

2
2
3
2
3

Input

4
1 2 3 4

Output

0
0
0
0

Input

5
3 3 3 3 3

Output

6
6
6
6
6

Input

8
1 2 1 4 2 1 4 1

Output

5
7
5
7
7
5
7
5

```python
n=int(input())
a=list(map(int,input().split()))
e=list(set(a))
s=0
t=[0]*200000
for i in a:
    t[i]+=1
for j in e:
    k=t[j]
    s+=(k*(k-1))//2
for u in a:
    print(s-t[u]+1)
```


p02865 NIKKEI Programming Contest 2019-2 - Sum of Two Integers

How many ways are there to choose two distinct positive integers totaling N, disregarding the order?

Constraints

* 1 \leq N \leq 10^6
* N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Examples

Input

4

Output

1

Input

999999

Output

499999

```python
N = int(input())
print(N // 2 - int(N // 2 * 2 == N))
```


p03000 AtCoder Beginner Contest 130 - Bounding

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.

Examples

Input

3 6
3 4 5

Output

2

Input

4 9
3 3 3 3

Output

4

```python
n, x = map(int, input().split())
l = [int(i) for i in input().split()]

d = 0
c = 0

for i in l:
	d += i

	if d <= x:
		c += 1

print(c+1)
```


p03141 NIKKEI Programming Contest 2019 - Different Strokes

There are N dishes of cuisine placed in front of Takahashi and Aoki. For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.

When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.

Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat. Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end".

Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Constraints

* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* 1 \leq B_i \leq 10^9
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Examples

Input

3
10 10
20 20
30 30

Output

20

Input

3
20 10
20 20
20 30

Output

20

Input

6
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Output

-2999999997

```python
N = int(input())
A, B = [], []
for i in range(N):
    a,b = map(int, input().split())
    A.append(a)
    B.append(b)

AB = sorted([s+t for s,t in zip(A,B)], reverse=True)
su = sum(AB[::2])
print(su-sum(B))
```


p03285 AtCoder Beginner Contest 105 - Cakes and Donuts

La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each. Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.

Constraints

* N is an integer between 1 and 100, inclusive.

Input

Input is given from Standard Input in the following format:

N

Output

If there is a way to buy some cakes and some doughnuts for exactly N dollars, print `Yes`; otherwise, print `No`.

Examples

Input

11

Output

Yes

Input

40

Output

Yes

Input

3

Output

No


p03441 AtCoder Petrozavodsk Contest 001 - Antennas on Tree

We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v.

It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices.

First, he decides the number of antennas, K (1 ≤ K ≤ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 ≤ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold:

* For each vertex u (0 ≤ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct.

Find the minumum value of K, the number of antennas, when the condition is satisfied.

Constraints

* 2 ≤ N ≤ 10^5
* 0 ≤ a_i, b_i < N
* The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_0 b_0
a_1 b_1
:
a_{N - 2} b_{N - 2}

Output

Print the minumum value of K, the number of antennas, when the condition is satisfied.

Examples

Input

5
0 1
0 2
0 3
3 4

Output

2

Input

2
0 1

Output

1

Input

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

Output

3

```python
import sys
readline = sys.stdin.readline
from collections import Counter
from random import randrange
def parorder(Edge, p):
    N = len(Edge)
    par = [0]*N
    par[p] = -1
    stack = [p]
    order = []
    visited = set([p])
    ast = stack.append
    apo = order.append
    while stack:
        vn = stack.pop()
        apo(vn)
        for vf in Edge[vn]:
            if vf in visited:
                continue
            visited.add(vf)
            par[vf] = vn
            ast(vf)
    return par, order

def getcld(p):
    res = [[] for _ in range(len(p))]
    for i, v in enumerate(p[1:], 1):
        res[v].append(i)
    return res

N = int(readline())
Edge = [[] for _ in range(N)]
Leaf = [0]*N
for _ in range(N-1):
    a, b = map(int, readline().split())
    Leaf[a] += 1
    Leaf[b] += 1
    Edge[a].append(b)
    Edge[b].append(a)

Leaf = [i for i in range(N) if Leaf[i] == 1]
M = len(Leaf)
ANS = 10**9+7
for idx in [0] + [randrange(1, M) for _ in range(10)]:
    root = Leaf[idx]
    P, L = parorder(Edge, root)
    C = getcld(P)

    dp = [0]*N
    countone = [0]*N
    for l in L[::-1][:-1]:
        p = P[l]
        dp[l] += 1 + max(0, countone[l] - 1)
        if dp[l] == 1:
            countone[p] += 1
        dp[p] += dp[l] - 1

    dp[root] += 1 + max(0, countone[root] - 1)
    ANS = min(ANS, dp[root])
print(ANS)
```


p03599 AtCoder Beginner Contest 074 - Sugar Water

Snuke is making sugar water in a beaker. Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.

* Operation 1: Pour 100A grams of water into the beaker.
* Operation 2: Pour 100B grams of water into the beaker.
* Operation 3: Put C grams of sugar into the beaker.
* Operation 4: Put D grams of sugar into the beaker.

In our experimental environment, E grams of sugar can dissolve into 100 grams of water.

Snuke will make sugar water with the highest possible density.

The beaker can contain at most F grams of substances (water and sugar combined), and there must not be any undissolved sugar in the beaker. Find the mass of the sugar water Snuke will make, and the mass of sugar dissolved in it. If there is more than one candidate, any of them will be accepted.

We remind you that the sugar water that contains a grams of water and b grams of sugar is \frac{100b}{a + b} percent. Also, in this problem, pure water that does not contain any sugar is regarded as 0 percent density sugar water.

Constraints

* 1 \leq A < B \leq 30
* 1 \leq C < D \leq 30
* 1 \leq E \leq 100
* 100A \leq F \leq 3 000
* A, B, C, D, E and F are all integers.

Inputs

Input is given from Standard Input in the following format:

A B C D E F

Outputs

Print two integers separated by a space. The first integer should be the mass of the desired sugar water, and the second should be the mass of the sugar dissolved in it.

Examples

Input

1 2 10 20 15 200

Output

110 10

Input

1 2 1 2 100 1000

Output

200 100

Input

17 19 22 26 55 2802

Output

2634 934

```python
a,b,c,d,e,f=map(int,input().split())
a100=a*100
b100=b*100
ok=[]
for ai in range(31):
  for bi in range(31):
    for ci in range(101):
      for di in range(101):
        ab= ai*a100+bi*b100
        cd= ci*c+di*d
        if ab + cd >f:
          break
        else:
          if (ab/100)*e>=cd:
            ok.append([ab+cd,cd])
#塩分濃度をキーとしてソートしている
print(*sorted(ok, key=lambda x: (100*x[1] / x[0] if x[0] else 0))[-1])
```


p03760 AtCoder Beginner Contest 058 - ∵∴∵

Snuke signed up for a new website which holds programming competitions. He worried that he might forget his password, and he took notes of it. Since directly recording his password would cause him trouble if stolen, he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions.

You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order. Restore the original password.

Constraints

* O and E consists of lowercase English letters (`a` - `z`).
* 1 \leq |O|,|E| \leq 50
* |O| - |E| is either 0 or 1.

Input

Input is given from Standard Input in the following format:

O
E

Output

Print the original password.

Examples

Input

xyz
abc

Output

xaybzc

Input

atcoderbeginnercontest
atcoderregularcontest

Output

aattccooddeerrbreeggiunlnaerrccoonntteesstt

```python
O = input()
E = input() + " "
for i in range(len(O)): print(O[i]+E[i],end="",sep="")

```


p03922 CODE FESTIVAL 2016 Final (Parallel) - Pair Cards

Takahashi is playing with N cards.

The i-th card has an integer X_i on it.

Takahashi is trying to create as many pairs of cards as possible satisfying one of the following conditions:

* The integers on the two cards are the same.
* The sum of the integers on the two cards is a multiple of M.

Find the maximum number of pairs that can be created.

Note that a card cannot be used in more than one pair.

Constraints

* 2≦N≦10^5
* 1≦M≦10^5
* 1≦X_i≦10^5

Input

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

N M
X_1 X_2 ... X_N

Output

Print the maximum number of pairs that can be created.

Examples

Input

7 5
3 1 4 1 5 9 2

Output

3

Input

15 10
1 5 6 10 11 11 11 20 21 25 25 26 99 99 99

Output

6

```python
import math

N, M = map(int, input().split())
X = list(map(int, input().split()))
mod_arr = [{} for i in range(M)]
for x in X:
    d = mod_arr[x % M]
    if x in d:
        d[x] += 1
    else:
        d[x] = 1
ans = 0

if M == 1:
    print(N // 2)
    exit()

def calc_only_one(d):
    sum_v = sum(d.values())
    return sum_v // 2

ans += calc_only_one(mod_arr[0])
# even pattern
if M % 2 == 0:
    ans += calc_only_one(mod_arr[M // 2])

def calc_two(d_S, d_T):
    res = 0
    if len(d_S) == 0:
        for v in d_T.values():
            res += v // 2
        return res
    elif len(d_T) == 0:
        for v in d_S.values():
            res += v // 2
        return res

    if sum(d_S.values()) < sum(d_T.values()):
        d_S, d_T = d_T, d_S
    cnt_S = sum(d_S.values())
    cnt_T = sum(d_T.values())
    remain_for_pair = cnt_S - cnt_T
    max_pair_cnt = sum([v // 2 for v in d_S.values()])
    pair_cnt = min(remain_for_pair // 2 , max_pair_cnt)
    res = cnt_T + pair_cnt
    # print(d_S, d_T)
    # print(remain_for_pair, max_pair_cnt, pair_cnt, res)
    return res

for i in range(1, math.ceil(M / 2)):
    ans += calc_two(mod_arr[i], mod_arr[M - i])
print(ans)

```


p00023 Circles Intersection

You are given circle $A$ with radius $r_a$ and with central coordinate $(x_a, y_a)$ and circle $B$ with radius $r_b$ and with central coordinate $(x_b, y_b)$.

Write a program which prints:

* "2" if $B$ is in $A$,
* "-2" if $A$ is in $B$,
* "1" if circumference of $A$ and $B$ intersect, and
* "0" if $A$ and $B$ do not overlap.

You may assume that $A$ and $B$ are not identical.

Input

The input consists of multiple datasets. The first line consists of an integer $N$ ($N \leq 50$), the number of datasets. There will be $N$ lines where each line represents each dataset. Each data set consists of real numbers:

$x_a$ $y_a$ $r_a$ $x_b$ $y_b$ $r_b$

Output

For each dataset, print 2, -2, 1, or 0 in a line.

Example

Input

2
0.0 0.0 5.0 0.0 0.0 4.0
0.0 0.0 2.0 4.1 0.0 2.0

Output

2
0

```python
n = int(input())

for _ in range(n):
    xa, ya, ra, xb, yb, rb = map(float, input().split())
    dist = ((xa - xb)**2 + (ya - yb)**2)**.5
    if ra + rb < dist:
        print('0')
    elif abs(ra - rb) <= dist:
        print('1')
    elif (rb < ra):
        print('2')
    elif (ra < rb):
        print('-2')
```


p00154 Sum of Cards

Let's play the game using a bag containing several cards with integers written on it. In each game, participants first declare one of their favorite number n. Then, take out an appropriate number of cards from the bag at a time, and if the sum of the numbers written on those cards is equal to n, you will receive a luxurious prize. After each game, the cards will be returned to the bag.

Create a program that inputs the information of m types of cards in the bag and the number declared by the participants in g games, and outputs how many combinations of cards can receive luxury products in each game. please.

Input

A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:

m
a1 b1
a2 b2
::
am bm
g
n1
n2
::
ng

The number of card types m (1 ≤ m ≤ 7) on the first line, the integer ai (1 ≤ ai ≤ 100) written on the i-type card on the following m line, and the number bi (1 ≤ bi ≤ 10) Are given with a space delimiter.

The next line is given the number of games g (1 ≤ g ≤ 10), and the next g line is given the integer ni (1 ≤ ni ≤ 1,000) declared in game i.

The number of datasets does not exceed 100.

Output

For each input dataset, the i line prints the number of card combinations that will give you a gorgeous prize in Game i.

Example

Input

5
1 10
5 3
10 3
25 2
50 2
4
120
500
100
168
7
1 10
3 10
5 10
10 10
25 10
50 10
100 10
3
452
574
787
0

Output

16
0
12
7
9789
13658
17466

```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
ans = []
while 1:
    M = int(readline())
    if M == 0:
        break
    P = [list(map(int, input().split())) for i in range(M)]
    memo = {}
    def dfs(i, rest):
        if i == M:
            return rest == 0
        key = (i, rest)
        if key in memo:
            return memo[key]
        res = 0
        a, b = P[i]
        for j in range(0, b+1):
            if rest - j*a < 0:
                break
            res += dfs(i+1, rest - j*a)
        memo[key] = res
        return res
    G = int(input())
    for i in range(G):
        ans.append(str(dfs(0, int(input()))))
write("\n".join(ans))
write("\n")

```


p00311 Fishing Competition

The brothers Hiroshi and Kenjiro came to Lake Inawashiro for fishing. The two decided to score as follows and compete with the total score of the fish they caught.

* One char is a point
* One yamame trout b points
* Add c points for every 10 chars
* Add d points for every 20 yamame trout

Create a program to determine which one wins or draws based on the number of fish caught by Hiroshi and Kenjiro.

Input

The input is given in the following format.

h1 h2
k1 k2
a b c d

The first line gives the number of chars h1 (0 ≤ h1 ≤ 100) and the number of yamame trout h2 (0 ≤ h2 ≤ 100) caught by Hiroshi. The second line gives the number of chars k1 (0 ≤ k1 ≤ 100) and the number of yamame trout k2 (0 ≤ k2 ≤ 100) caught by Kenjiro. On the third line, the score for each char is a (1 ≤ a ≤ 100), the score for each yamame trout is b (1 ≤ b ≤ 100), and the additional score for every 10 chars is c (0 ≤ c ≤ 100). ), An additional score d (0 ≤ d ≤ 100) is given for every 20 chars.

Output

If Hiro wins, hiroshi, if Kenjiro wins, kenjiro, and if a tie, even, output on one line.

Examples

Input

5 1
3 1
1 2 5 5

Output

hiroshi

Input

5 1
4 2
1 2 5 5

Output

kenjiro

Input

0 20
10 0
1 1 10 0

Output

even

```python
def main():
    h1, h2 = map(int, input().split())
    k1, k2 = map(int, input().split())
    a, b, c, d = map(int, input().split())

    hiroshi = h1 * a + int(h1 / 10) * c + h2 * b + int(h2 / 20) *d
    kenjiro = k1 * a + int(k1 / 10) * c + k2 * b + int(k2 / 20) *d

    if hiroshi > kenjiro:
        print('hiroshi')
    elif kenjiro > hiroshi:
        print('kenjiro')
    else:
        print('even')

if __name__ == '__main__':
    main()
```


p00475 Exposition

problem

JOI City will hold a large-scale exposition.

There are two themes for this exposition, and each of the N exhibition facilities in JOI City will exhibit on one of the two themes.

The location of the facility is represented by plane coordinates (x, y). To move from the facility at position (x, y) to the facility at (x ′, y ′), | x − x ′ | + It takes only | y − y ′ | (for the integer a, | a | represents the absolute value of a). To create a sense of unity within the same theme, and to be interested in only one theme. In order not to make people feel inconvenience, I would like to assign the theme so that the travel time between two facilities exhibiting on the same theme is as short as possible. Unless the same theme is assigned to all exhibition facilities. , How can you divide the theme.

Let M be the maximum travel time between two facilities exhibiting on the same theme. Create a program to find the minimum value of M given the locations of N exhibition facilities.

output

The output consists of only one line. Output the maximum value M of the maximum travel time between two facilities exhibiting on the same theme.

Input / output example

Input example 1

Five
0 0
Ten
-1 -2
0 1
-1 1

Output example 1

3

In this case, for example, one theme for the facility at coordinates (0, 0), (1, 0), (0, 1), and another theme for the facility at (−1, −2), (−1, 1). When one theme is assigned, the travel time between two facilities exhibiting on the same theme is all 3 or less. Since the travel time cannot be all 2 or less, 3 is output.

The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.

input

The first line of input contains the number of facilities N (3 ≤ N ≤ 100000 = 105). The first line of input i + 1 (1 ≤ i ≤ N) represents the coordinates of each facility. The two integers xi, yi (| xi | ≤ 100000 = 105, | yi | ≤ 100000 = 105) are separated by blanks. This is where the coordinates of the i-th facility are (xi, yi). It means that there can be no more than one facility at the same coordinates.

Of the scoring data, 40% of the points are N ≤ 2000.

Example

Input

5
0 0
1 0
-1 -2
0 1
-1 1

Output

3

```python
# AOJ 0552: Exposition
# Python3 2018.7.1 bal4u

import sys
from sys import stdin
input = stdin.readline

x, y = [], []
n = int(input())
for i in range(n):
	a, b = map(int, input().split())
	x.append(a+b)
	y.append(a-b)
xmin, xmax = min(x), max(x)
ymin, ymax = min(y), max(y)
ans1 = ans2 = 0
for i in range(n):
	d1 = max(x[i]-xmin, y[i]-ymin)
	d2 = max(xmax-x[i], ymax-y[i])
	ans1 = max(ans1, min(d1, d2))

	d1 = max(x[i]-xmin, ymax-y[i])
	d2 = max(xmax-x[i], y[i]-ymin)
	ans2 = max(ans2, min(d1, d2))
print(min(ans1, ans2))

```


p00667 11224111122411

My arm is stuck and I can't pull it out.

I tried to pick up something that had rolled over to the back of my desk, and I inserted my arm while illuminating it with the screen of my cell phone instead of a flashlight, but I accidentally got caught in something and couldn't pull it out. It hurts if you move it forcibly.

What should I do. How can I escape? Do you call for help out loud? I'm embarrassed to dismiss it, but it seems difficult to escape on my own. No, no one should have been within reach. Hold down your impatience and look around. If you can reach that computer, you can call for help by email, but unfortunately it's too far away. After all, do we have to wait for someone to pass by by chance?

No, wait, there is a machine that sends emails. It's already in your hands, rather than within reach. The screen at the tip of my deeply extended hand is blurry and hard to see, but it's a mobile phone I've been using for many years. You should be able to send emails even if you can't see the screen.

Carefully press the button while drawing the screen in your head. Rely on the feel of your finger and type in a message by pressing the number keys many times to avoid making typos. It doesn't convert to kanji, and it should be transmitted even in hiragana. I'm glad I didn't switch to the mainstream smartphones for the touch panel.

Take a deep breath and put your finger on the send button. After a while, my cell phone quivered lightly. It is a signal that the transmission is completed. sigh. A friend must come to help after a while.

I think my friends are smart enough to interpret it properly, but the message I just sent may be different from the one I really wanted to send. The character input method of this mobile phone is the same as the widely used one, for example, use the "1" button to input the hiragana of the "A" line. "1" stands for "a", "11" stands for "i", and so on, "11111" stands for "o". Hiragana loops, that is, "111111" also becomes "a". The "ka" line uses "2", the "sa" line uses "3", ..., and the behavior when the same button is pressed in succession is the same as in the example of "1".

However, this character input method has some annoying behavior. If you do not operate for a while after pressing the number button, the conversion to hiragana will be forced. In other words, if you press "1" three times in a row, it will become "U", but if you press "1" three times after a while, it will become "Ah". To give another example, when you press "111111", the character string entered depends on the interval between the presses, which can be either "a" or "ah ah ah". "111111111111" may be "yes", "yeah ah", or twelve "a". Note that even if you press a different number button, it will be converted to hiragana, so "12345" can only be the character string "Akasatana".

Well, I didn't mean to press the wrong button because I typed it carefully, but I'm not confident that I could press the buttons at the right intervals. It's very possible that you've sent something different than the message you really wanted to send. Now, how many strings may have been sent? Oh, this might be a good way to kill time until a friend comes to help. They will come to help within 5 hours at the latest. I hope it can be solved by then.

Input

The input consists of multiple cases.
Each case is given in the following format.

string

The end of the input is given by the line where the input consists of "#"

string contains up to 100,000 numbers between 0 and 9.
No more than 50 inputs have a string length greater than 10,000.

The test case file size is guaranteed to be 5MB or less.
Also, the number of test cases does not exceed 100.

The characters that can be entered with each number key are as shown in the table below.

Numbers | Enterable characters
--- | ---
1 | Aiueo
2 | Kakikukeko
3 |
4 |
5 | What is it?
6 | Hahifuheho
7 | Mamimumemo
8 | Yayuyo
9 | Larry Lero
0 | Won

Output

Divide how to interpret the sentence by 1000000007 and output the remainder on one line.

Examples

Input

1
11
111111
111111111111
12345
11111111119999999999
11111111113333333333
11111111118888888888
11111111112222222222111111111
11111111110000000000444444444
11224111122411
888888888888999999999999888888888888999999999999999999
666666666666666777333333333338888888888
1111114444441111111444499999931111111222222222222888111111115555
#

Output

1
2
32
1856
1
230400
230400
156480
56217600
38181120
128
26681431
61684293
40046720

Input

1
11
111111
111111111111
12345
11111111119999999999
11111111113333333333
11111111118888888888
11111111112222222222111111111
11111111110000000000444444444
11224111122411
888888888888999999999999888888888888999999999999999999
666666666666666777333333333338888888888
1111114444441111111444499999931111111222222222222888111111115555

Output

1
2
32
1856
1
230400
230400
156480
56217600
38181120
128
26681431
61684293
40046720

```python
def f3(n):
    a=b=c=0
    for _ in range(n):
        a,b,c=(a+b+c+1)%100000007,a,b
    return a

def f5(n):
    a=b=c=d=e=0
    for _ in range(n):
        a,b,c,d,e=(a+b+c+d+e+1)%100000007,a,b,c,d
    return a

while 1:
    s=input()
    if s=="#":break
    ans=1
    num="_"
    cnt=1
    for n in s+"_":
        if n==num:
            cnt+=1
        else:
            if num in "80":
                ans=ans*f3(cnt)%100000007
            else:
                ans=ans*f5(cnt)%100000007
            num=n
            cnt=1
    print(ans)

```


p00810 Super Star

During a voyage of the starship Hakodate-maru (see Problem A), researchers found strange synchronized movements of stars. Having heard these observations, Dr. Extreme proposed a theory of "super stars". Do not take this term as a description of actors or singers. It is a revolutionary theory in astronomy.

According to this theory, stars we are observing are not independent objects, but only small portions of larger objects called super stars. A super star is filled with invisible (or transparent) material, and only a number of points inside or on its surface shine. These points are observed as stars by us.

In order to verify this theory, Dr. Extreme wants to build motion equations of super stars and to compare the solutions of these equations with observed movements of stars. As the first step, he assumes that a super star is sphere-shaped, and has the smallest possible radius such that the sphere contains all given stars in or on it. This assumption makes it possible to estimate the volume of a super star, and thus its mass (the density of the invisible material is known).

You are asked to help Dr. Extreme by writing a program which, given the locations of a number of stars, finds the smallest sphere containing all of them in or on it. In this computation, you should ignore the sizes of stars. In other words, a star should be regarded as a point. You may assume the universe is a Euclidean space.

Input

The input consists of multiple data sets. Each data set is given in the following format.

n
x1 y1 z1
x2 y2 z2
...
xn yn zn

The first line of a data set contains an integer n, which is the number of points. It satisfies the condition 4 ≤ n ≤ 30.

The locations of n points are given by three-dimensional orthogonal coordinates: (xi, yi, zi) (i = 1,..., n). Three coordinates of a point appear in a line, separated by a space character.

Each value is given by a decimal fraction, and is between 0.0 and 100.0 (both ends inclusive). Points are at least 0.01 distant from each other.

The end of the input is indicated by a line containing a zero.

Output

For each data set, the radius ofthe smallest sphere containing all given points should be printed, each in a separate line. The printed values should have 5 digits after the decimal point. They may not have an error greater than 0.00001.

Example

Input

4
10.00000 10.00000 10.00000
20.00000 10.00000 10.00000
20.00000 20.00000 10.00000
10.00000 20.00000 10.00000
4
10.00000 10.00000 10.00000
10.00000 50.00000 50.00000
50.00000 10.00000 50.00000
50.00000 50.00000 10.00000
0

Output

7.07107
34.64102

```python
def distance(star, position):
    return sum([(a - b)**2 for a, b in zip(star, position)])**(1 / 2)

def difference(star, position):
    return [(a - b) for a, b in zip(star, position)]

while True:
    n = int(input())
    if n == 0:
        break
    stars = [list(map(float, input().split())) for i in range(n)]
    position = [sum([s[i] for s in stars]) / len(stars) for i in range(3)]
    move_rate = 1
    for i in range(3000):
        if i % 100 == 0:
            move_rate /= 2
        index = 0
        dis_max = 0
        for j, star in enumerate(stars):
            dis = distance(star, position)
            if dis_max < dis:
                dis_max = dis
                index = j
        diff = difference(stars[index], position)
        position = [(position[i] + diff[i] * move_rate) for i in range(3)]

    print(format(dis_max, ".5f"))

```


p00941 Do Geese See God?

Example

Input

crc
1

Output

crc

```python
from heapq import heappush, heappop

def solve():
    S = input()
    K = int(input())
    L = len(S)
    INF = 10**9
    cost = [[INF]*(L+1) for i in range(L+1)]
    cost[0][L] = 0
    ss = []
    que = [(0, 0, L)]
    while que:
        d, a, b = heappop(que)
        if cost[a][b] < d:
            continue
        ss.append((a, b))
        if a+1 == b:
            if d+1 < cost[a+1][b]:
                cost[a+1][b] = d + 1
            continue
        if S[a] == S[b-1]:
            if d+2 < cost[a+1][b-1]:
                cost[a+1][b-1] = d + 2
                if a+1 < b-1:
                    heappush(que, (d+2, a+1, b-1))
        else:
            if d+2 < cost[a+1][b]:
                cost[a+1][b] = d + 2
                if a+1 < b:
                    heappush(que, (d+2, a+1, b))
            if d+2 < cost[a][b-1]:
                cost[a][b-1] = d + 2
                if a < b-1:
                    heappush(que, (d+2, a, b-1))
    ln = min(cost[i][i] for i in range(L+1))
    ss.reverse()
    dp = [[0]*(L+1) for i in range(L+1)]
    for i in range(L+1):
        if cost[i][i] == ln:
            dp[i][i] = 1
    for a, b in ss:
        d = cost[a][b]
        r = 0
        if a+1 == b:
            if d+1 == cost[a+1][b]:
                r = dp[a+1][b]
        else:
            if S[a] == S[b-1]:
                if d+2 == cost[a+1][b-1]:
                    r = dp[a+1][b-1]
            else:
                if d+2 == cost[a+1][b]:
                    r += dp[a+1][b]
                if d+2 == cost[a][b-1]:
                    r += dp[a][b-1]
        dp[a][b] = r
    if dp[a][b] < K:
        print("NONE")
        return True
    SL = []; SR = []
    a = 0; b = L
    while a < b:
        if a+1 == b:
            assert cost[a][b]+1 == cost[a+1][b]
            SL.append(S[a])
            a += 1
            continue
        if S[a] == S[b-1]:
            assert cost[a][b]+2 == cost[a+1][b-1]
            SL.append(S[a])
            SR.append(S[b-1])
            a += 1; b -= 1
        elif S[a] < S[b-1]:
            c = (cost[a][b]+2 == cost[a+1][b])
            if c and K <= dp[a+1][b]:
                SL.append(S[a])
                SR.append(S[a])
                a += 1
            else:
                if c:
                    K -= dp[a+1][b]
                SL.append(S[b-1])
                SR.append(S[b-1])
                b -= 1
        else:
            c = (cost[a][b]+2 == cost[a][b-1])
            if c and K <= dp[a][b-1]:
                SL.append(S[b-1])
                SR.append(S[b-1])
                b -= 1
            else:
                if c:
                    K -= dp[a][b-1]
                SL.append(S[a])
                SR.append(S[a])
                a += 1
    SR.reverse()
    SL.extend(SR)
    print("".join(SL))
solve()

```


p01074 Unhappy Class

Problem

Yamano Mifune Gakuen's 1st grade G group is a class where female students carrying misfortune gather. They face various challenges every day with the goal of being happy.

In their class, they can take practical happiness courses as part of the test of happiness.
From Monday to Friday, there are classes from 1st to Nth, and there are M courses that can be taken.

Subject i starts from the ai period of the day of the week di (di = 0, 1, 2, 3, 4 corresponds to Monday, Tuesday, Wednesday, Thursday, and Friday, respectively), and is performed in consecutive ki frames. The degree of happiness obtained when taking the course is ti.

Each student is free to choose up to L subjects so that they do not overlap each other. How do you choose the subject to get the highest level of happiness? Please find the maximum value of happiness that can be obtained from the information of the given subject.

Constraints

* 2 ≤ N ≤ 8
* 0 ≤ M ≤ 300
* 0 ≤ L ≤ min (N × 5, M)
* 0 ≤ di ≤ 4
* 1 ≤ ai ≤ N
* 1 ≤ ki
* ai + ki --1 ≤ N
* 1 ≤ ti ≤ 100

Input

The input is given in the following format.

N M L
d1 a1 k1 t1
d2 a2 k2 t2
...
dM aM kM tM

The first line is given three integers N, M, L separated by blanks.
The four integers di, ai, ki, and ti are given on the 2nd to M + 1th lines, separated by blanks.

Output

Output the maximum value of the sum of happiness on one line.

Examples

Input

3 7 3
0 1 1 1
0 1 1 2
1 1 3 4
1 1 1 1
1 2 1 2
2 1 1 3
2 2 2 1

Output

9

Input

5 10 5
0 1 1 2
0 2 1 2
0 1 2 3
1 2 1 2
1 4 2 3
2 1 1 1
2 1 1 2
3 3 2 3
4 1 1 2
4 2 1 2

Output

13

```python
from itertools import product

n, m, l = map(int, input().split())
subjects = [[] for _ in range(5)]
for _ in range(m):
    d, a, k, t = map(int, input().split())
    subjects[d].append((a, a + k - 1, t))

for i in range(5):
    subjects[i].sort(key=lambda x:x[1])

#各曜日の科目数ごとの最大幸福
def calcDp(i):
    #dp[y][x] ... y科目xコマまでの最大幸福
    dp = [[0] * (n + 1) for _ in range(n + 1)]
    sub = subjects[i]
    for init, end, value in sub:
        for y in range(n):
            new_score = dp[y][init - 1] + value
            for x in range(end, n + 1):
                dp[y + 1][x] = max(dp[y + 1][x], new_score)
    ret = []
    for i in range(n + 1):
        ret.append(max(dp[i]))
    return ret

lst = [calcDp(i) for i in range(5)]

ans = 0
for t in product(range(n + 1), repeat=5):
    if sum(t) > l:continue
    score = 0
    for i, v in enumerate(t):
        score += lst[i][v]
    ans = max(score, ans)
print(ans)

```


p02248 String Search

Find places where a string P is found within a text T. Print all indices of T where P found. The indices of T start with 0.

Constraints

* 1 ≤ length of T ≤ 1000000
* 1 ≤ length of P ≤ 10000
* The input consists of alphabetical characters and digits

Input

In the first line, a text T is given. In the second line, a string P is given.

Output

Print an index of T where P found in a line. Print the indices in ascending order.

Examples

Input

aabaaa
aa

Output

0
3
4

Input

xyzz
yz

Output

1

Input

abc
xyz

Output

```python
s=input();t=input()
[print(x) for x in range(len(s)-len(t)+1) if s[x:x+len(t)]==t]
```


p02396 Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Constraints

* 1 ≤ x ≤ 10000
* The number of datasets ≤ 10000

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Example

Input

3
5
11
7
8
19
0

Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19

```python
i = 0

while True:
 n = int(input())
 i += 1
 if n == 0:
  break
 print("Case {}: {}".format(i, n))
```


1015_B. Obtaining the String

You are given two strings s and t. Both strings have length n and consist of lowercase Latin letters. The characters in the strings are numbered from 1 to n.

You can successively perform the following move any number of times (possibly, zero):

  * swap any two adjacent (neighboring) characters of s (i.e. for any i = \{1, 2, ..., n - 1\} you can swap s_i and s_{i + 1}).

You can't apply a move to the string t. The moves are applied to the string s one after another.

Your task is to obtain the string t from the string s. Find any way to do it with at most 10^4 such moves.

You do not have to minimize the number of moves, just find any sequence of moves of length 10^4 or less to transform s into t.

Input

The first line of the input contains one integer n (1 ≤ n ≤ 50) — the length of strings s and t.

The second line of the input contains the string s consisting of n lowercase Latin letters.

The third line of the input contains the string t consisting of n lowercase Latin letters.

Output

If it is impossible to obtain the string t using moves, print "-1".

Otherwise in the first line print one integer k — the number of moves to transform s to t. Note that k must be an integer number between 0 and 10^4 inclusive.

In the second line print k integers c_j (1 ≤ c_j < n), where c_j means that on the j-th move you swap characters s_{c_j} and s_{c_j + 1}.

If you do not need to apply any moves, print a single integer 0 in the first line and either leave the second line empty or do not print it at all.

Examples

Input

6
abcdef
abdfec

Output

4
3 5 4 5

Input

4
abcd
accd

Output

-1

Note

In the first example the string s changes as follows: "abcdef" → "abdcef" → "abdcfe" → "abdfce" → "abdfec".

In the second example there is no way to transform the string s into the string t through any allowed moves.

```python
n = int(input())
s = input()
t = input()
if s == t:
    print(0)
elif sorted(s) != sorted(t):
    print(-1)
else:
    res = list()
    ls = list(s)
    lt = list(t)
    for i in range(n):
        if ls[i] != lt[i]:
            pos = ls.index(lt[i], i+1)
            j = pos-1
            while j >= i:
                ls[j], ls[j+1] = ls[j+1], ls[j]
                res.append(j+1)
                j -= 1
    print(len(res))
    print(*res)

```


1038_F. Wrap Around

You are given a binary string s.

Find the number of distinct cyclical binary strings of length n which contain s as a substring.

The cyclical string t contains s as a substring if there is some cyclical shift of string t, such that s is a substring of this cyclical shift of t.

For example, the cyclical string "000111" contains substrings "001", "01110" and "10", but doesn't contain "0110" and "10110".

Two cyclical strings are called different if they differ from each other as strings. For example, two different strings, which differ from each other by a cyclical shift, are still considered different cyclical strings.

Input

The first line contains a single integer n (1 ≤ n ≤ 40) — the length of the target string t.

The next line contains the string s (1 ≤ |s| ≤ n) — the string which must be a substring of cyclical string t. String s contains only characters '0' and '1'.

Output

Print the only integer — the number of distinct cyclical binary strings t, which contain s as a substring.

Examples

Input

2
0

Output

3

Input

4
1010

Output

2

Input

20
10101010101010

Output

962

Note

In the first example, there are three cyclical strings, which contain "0" — "00", "01" and "10".

In the second example, there are only two such strings — "1010", "0101".

```python
n=int(input())
s=[c=='1' for c in input()]
m=len(s)
z=[[0,0]]
for c in s:
 ind = z[-1][c]
 z[-1][c] = len(z)
 z.append(z[ind][:])
assert(len(z) == m+1)
z[m][0] = z[m][1] = m # make it sticky

# how many things match directly
dp = [0 for _ in range(m+1)]
dp[0] = 1
for i in range(n):
 ndp = [0 for _ in range(m+1)]
 for i in range(m+1):
  ndp[z[i][0]] += dp[i]
  ndp[z[i][1]] += dp[i]
 dp = ndp
res = dp[m]

for k in range(1, m):
 s0 = 0
 for c in s[-k:]:
  s0 = z[s0][c]
 dp = [0 for _ in range(m+1)]
 dp[s0] = 1
 for i in range(n - k):
  ndp = [0 for _ in range(m+1)]
  for i in range(m+1):
   ndp[z[i][0]] += dp[i]
   ndp[z[i][1]] += dp[i]
  dp = ndp
 for s1 in range(m): # skip m
  v = dp[s1]
  for c in s[-k:]:
   if s1 == m: v = 0
   s1 = z[s1][c]
  if s1 == m: res += v
print(res)
```


1061_B. Views Matter

You came to the exhibition and one exhibit has drawn your attention. It consists of n stacks of blocks, where the i-th stack consists of a_i blocks resting on the surface.

The height of the exhibit is equal to m. Consequently, the number of blocks in each stack is less than or equal to m.

There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks.

<image>

Find the maximum number of blocks you can remove such that the views for both the cameras would not change.

Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.

Input

The first line contains two integers n and m (1 ≤ n ≤ 100 000, 1 ≤ m ≤ 10^9) — the number of stacks and the height of the exhibit.

The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ m) — the number of blocks in each stack from left to right.

Output

Print exactly one integer — the maximum number of blocks that can be removed.

Examples

Input

5 6
3 3 3 3 3

Output

10

Input

3 5
1 2 4

Output

3

Input

5 5
2 3 1 4 4

Output

9

Input

1 1000
548

Output

0

Input

3 3
3 1 1

Output

1

Note

The following pictures illustrate the first example and its possible solution.

Blue cells indicate removed blocks. There are 10 blue cells, so the answer is 10.

<image>

```python
n,m=map(int,input().split(' '))
a=list(map(int,input().split(' ')))
a.sort()
count=0
prev=0
for i in range(n):
    count+=1
    if a[i]>prev:
        prev+=1
count+=a[n-1]-prev
print(sum(a)-count)

```


1083_A. The Fair Nut and the Best Path

The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex.

A filling station is located in every city. Because of strange law, Nut can buy only w_i liters of gasoline in the i-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last.

He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it.

Input

The first line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of cities.

The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_{i} ≤ 10^9) — the maximum amounts of liters of gasoline that Nut can buy in cities.

Each of the next n - 1 lines describes road and contains three integers u, v, c (1 ≤ u, v ≤ n, 1 ≤ c ≤ 10^9, u ≠ v), where u and v — cities that are connected by this road and c — its length.

It is guaranteed that graph of road connectivity is a tree.

Output

Print one number — the maximum amount of gasoline that he can have at the end of the path.

Examples

Input

3
1 3 3
1 2 2
1 3 2

Output

3

Input

5
6 3 2 5 0
1 2 10
2 3 3
2 4 1
1 5 1

Output

7

Note

The optimal way in the first example is 2 → 1 → 3.

<image>

The optimal way in the second example is 2 → 4.

<image>

```python
import sys
input = sys.stdin.readline

n = int(input())
a = list(map(int, input().split()))
adj = [[] for i in range(n)]
for i in range(n-1):
    u, v, w = map(int, input().split())
    u -= 1
    v -= 1
    adj[u].append((v, w))
    adj[v].append((u, w))
best = [0] * n
ans = 0

def dfs(u):
    stack = list()
    visit = [False] * n
    stack.append((u, -1))
    while stack:
        u, par = stack[-1]
        if not visit[u]:
            visit[u] = True
            for v, w in adj[u]:
                if v != par:
                    stack.append((v, u))
        else:
            cand = []
            for v, w in adj[u]:
                if v != par:
                    cand.append(best[v] + a[v] - w)
            cand.sort(reverse=True)
            cur = a[u]
            for i in range(2):
                if i < len(cand) and cand[i] > 0:
                    cur += cand[i]
            global ans
            ans = max(ans, cur)
            best[u] = cand[0] if len(cand) > 0 and cand[0] > 0 else 0
            stack.pop()

dfs(0)
print(ans)
```


1102_C. Doors Breaking and Repairing

You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.

There are n doors, the i-th door initially has durability equal to a_i.

During your move you can try to break one of the doors. If you choose door i and its current durability is b_i then you reduce its durability to max(0, b_i - x) (the value x is given).

During Slavik's move he tries to repair one of the doors. If he chooses door i and its current durability is b_i then he increases its durability to b_i + y (the value y is given). Slavik cannot repair doors with current durability equal to 0.

The game lasts 10^{100} turns. If some player cannot make his move then he has to skip it.

Your goal is to maximize the number of doors with durability equal to 0 at the end of the game. You can assume that Slavik wants to minimize the number of such doors. What is the number of such doors in the end if you both play optimally?

Input

The first line of the input contains three integers n, x and y (1 ≤ n ≤ 100, 1 ≤ x, y ≤ 10^5) — the number of doors, value x and value y, respectively.

The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5), where a_i is the initial durability of the i-th door.

Output

Print one integer — the number of doors with durability equal to 0 at the end of the game, if you and Slavik both play optimally.

Examples

Input

6 3 2
2 3 1 3 4 2

Output

6

Input

5 3 3
1 2 4 2 3

Output

2

Input

5 5 6
1 2 6 10 3

Output

2

Note

Clarifications about the optimal strategy will be ignored.

```python
n, x, y = map(int, input().split())
a = list(map(int,input().split()))

if x > y:
    print( n )
else:
    m = 0
    for i in a:
        if i <= x:
            m += 1
    print( m - m // 2 )

```


1130_C. Connect

Alice lives on a flat planet that can be modeled as a square grid of size n × n, with rows and columns enumerated from 1 to n. We represent the cell at the intersection of row r and column c with ordered pair (r, c). Each cell in the grid is either land or water.

<image> An example planet with n = 5. It also appears in the first sample test.

Alice resides in land cell (r_1, c_1). She wishes to travel to land cell (r_2, c_2). At any moment, she may move to one of the cells adjacent to where she is—in one of the four directions (i.e., up, down, left, or right).

Unfortunately, Alice cannot swim, and there is no viable transportation means other than by foot (i.e., she can walk only on land). As a result, Alice's trip may be impossible.

To help Alice, you plan to create at most one tunnel between some two land cells. The tunnel will allow Alice to freely travel between the two endpoints. Indeed, creating a tunnel is a lot of effort: the cost of creating a tunnel between cells (r_s, c_s) and (r_t, c_t) is (r_s-r_t)^2 + (c_s-c_t)^2.

For now, your task is to find the minimum possible cost of creating at most one tunnel so that Alice could travel from (r_1, c_1) to (r_2, c_2). If no tunnel needs to be created, the cost is 0.

Input

The first line contains one integer n (1 ≤ n ≤ 50) — the width of the square grid.

The second line contains two space-separated integers r_1 and c_1 (1 ≤ r_1, c_1 ≤ n) — denoting the cell where Alice resides.

The third line contains two space-separated integers r_2 and c_2 (1 ≤ r_2, c_2 ≤ n) — denoting the cell to which Alice wishes to travel.

Each of the following n lines contains a string of n characters. The j-th character of the i-th such line (1 ≤ i, j ≤ n) is 0 if (i, j) is land or 1 if (i, j) is water.

It is guaranteed that (r_1, c_1) and (r_2, c_2) are land.

Output

Print an integer that is the minimum possible cost of creating at most one tunnel so that Alice could travel from (r_1, c_1) to (r_2, c_2).

Examples

Input

5
1 1
5 5
00001
11111
00111
00110
00110

Output

10

Input

3
1 3
3 1
010
101
010

Output

8

Note

In the first sample, a tunnel between cells (1, 4) and (4, 5) should be created. The cost of doing so is (1-4)^2 + (4-5)^2 = 10, which is optimal. This way, Alice could walk from (1, 1) to (1, 4), use the tunnel from (1, 4) to (4, 5), and lastly walk from (4, 5) to (5, 5).

In the second sample, clearly a tunnel between cells (1, 3) and (3, 1) needs to be created. The cost of doing so is (1-3)^2 + (3-1)^2 = 8.

```python
#complexity - O(n^2)
import math
import sys

sys.setrecursionlimit(2600)

class UnionFind():
  def __init__(self, num_elements):
    self.parent = list(range(num_elements))
    self.rank = [1] * num_elements

  def union(self, a, b):
    par_a = self.find(a)
    par_b = self.find(b)

    if par_a == par_b:
      return

    if self.rank[par_a] > self.rank[par_b]:
      self.parent[par_b] = par_a
      self.rank[par_a] = self.rank[par_a] + self.rank[par_b]
    else:
      self.parent[par_a] = par_b
      self.rank[par_b] = self.rank[par_a] + self.rank[par_b]

  def find(self, a):
    if self.parent[a] == a:
      return a
    par_a = self.find(self.parent[a])
    curr_parent = self.parent[a]
    if par_a != curr_parent:
      self.rank[curr_parent] -= self.rank[a]
      self.parent[a] = par_a

    return par_a

n = int(input())
r1, c1 = map(lambda x:int(x)-1, input().split())
r2, c2 = map(lambda x:int(x)-1, input().split())

arr = []
for i in range(n):
  arr.append(input())

def dfs():
  seen = set()
  directions = [(-1, 0), (0, -1), (0, 1), (1, 0)]
  uf = UnionFind(n*n)

  def find_index(i, j):
    return i*n+j

  def _dfs(i, j):
    if (i, j) in seen:
      return
    seen.add((i, j))
    if arr[i][j] == '1':
      return
    for direction in directions:
      ni, nj = i+direction[0], j+direction[1]
      if ni >= 0 and ni < n and nj >= 0 and nj < n and (ni, nj) not in seen and arr[ni][nj] == '0':
        uf.union(i*n+j, ni*n+nj)
        _dfs(ni, nj)

  for i in range(n):
    for j in range(n):
      _dfs(i, j)

  if uf.find(r1*n+c1) == uf.find(r2*n+c2):
    return 0
  parent1 = uf.find(r1*n+c1)
  parent2 = uf.find(r2*n+c2)
  min_distance = math.inf
  set_a = set()
  set_b = set()

  for i in range(n):
    for j in range(n):
      parent = uf.find(find_index(i, j))
      if parent == parent1:
        set_a.add((i, j))
      elif parent == parent2:
        set_b.add((i, j))

  for el1 in set_a:
    for el2 in set_b:
      dist = pow(el1[0]-el2[0], 2) + pow(el1[1]-el2[1], 2)
      min_distance = min(min_distance, dist)

  return min_distance

print(dfs())

```


1190_A. Tokitsukaze and Discard Items

Recently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 ≤ m ≤ n) special items of them.

These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.

Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.

<image> Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10.

Tokitsukaze wants to know the number of operations she would do in total.

Input

The first line contains three integers n, m and k (1 ≤ n ≤ 10^{18}, 1 ≤ m ≤ 10^5, 1 ≤ m, k ≤ n) — the number of items, the number of special items to be discarded and the number of positions in each page.

The second line contains m distinct integers p_1, p_2, …, p_m (1 ≤ p_1 < p_2 < … < p_m ≤ n) — the indices of special items which should be discarded.

Output

Print a single integer — the number of operations that Tokitsukaze would do in total.

Examples

Input

10 4 5
3 5 7 10

Output

3

Input

13 4 5
7 8 9 10

Output

1

Note

For the first example:

  * In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5;
  * In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7;
  * In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10.

For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once.

```python
##n,m,k=list(map(int,input().split()))
##p=list(map(int,input().split()))
##p.sort()
##import math
##ok=k
##ip=0
##s=1
##cnt=0
##a=False
##for i in p:
##
##    if ip<i<=k:
##
##        cnt+=1
##
##        a=True
##    elif ip<i<=k+cnt:
##
##        s+=1
##        k+=cnt+1
##        a=True
##
##
##    else:
##        if ip==0 and k+cnt==ok:
##            s=0
##        l=math.ceil((i-k)/ok)
##        ip=k+ok*(l-1)
##
##        k+=ok*l
##
##        s+=1
##
##        cnt=0
##
##
##
##
##
##
##print(s)
##
##
##
##
##
import math
n,m,k=list(map(int,input().split()))
p=list(map(int,input().split()))
p.sort()
ok=k
ip=0
s=0
if ok==1:
    print(len(p))
else:
    while ip<n and p:
        m=False
        cnt=0
        o=0
        while o<len(p):

            if ip<p[o] and p[o]<=k:

                m=True
                cnt+=1
                p.pop(o)
                o-=1
            else:

                break
            o+=1
        if m:
            s+=1

            k+=cnt

        else:

            l=math.ceil((p[o]-k)/ok)

            ip=k+ok*(l-1)
            k+=ok*l

    print(s)

```


1209_E1. Rotate Columns (easy version)

This is an easier version of the next problem. The difference is only in constraints.

You are given a rectangular n × m matrix a. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.

After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for i-th row it is equal r_i. What is the maximal possible value of r_1+r_2+…+r_n?

Input

The first line contains an integer t (1 ≤ t ≤ 40), the number of test cases in the input.

The first line of each test case contains integers n and m (1 ≤ n ≤ 4, 1 ≤ m ≤ 100) — the number of rows and the number of columns in the given matrix a.

Each of the following n lines contains m integers, the elements of a (1 ≤ a_{i, j} ≤ 10^5).

Output

Print t integers: answers for all test cases in the order they are given in the input.

Example

Input

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

Output

12
29

Note

In the first test case, you can shift the third column down by one, this way there will be r_1 = 5 and r_2 = 7.

In the second case you can don't rotate anything at all, this way there will be r_1 = r_2 = 10 and r_3 = 9.

```python

def naiveSolve():

    return

def main():

    t=int(input())
    allans=[]
    for _ in range(t):
        n,m=readIntArr()
        grid=[]
        for __ in range(n):
            grid.append(readIntArr())
        columns=[]
        for col in range(m):
            temp=[grid[i][col] for i in range(n)]
            columns.append(temp)

        valCol=[] # (value, column)
        for i in range(n):
            for j in range(m):
                valCol.append((grid[i][j],j))
        valCol.sort(reverse=True)

        # try all possible shifts for top n columns
        topCols=set()
        for val,col in valCol:
            topCols.add(col)
            if len(topCols)==n:
                break

        # try all configurations
        m2=len(topCols)
        grid2=[[-1 for __ in range(m2)] for ___ in range(n)]
        topColsList=list(topCols)
        for j in range(m2):
            col=topColsList[j]
            for i in range(n):
                grid2[i][j]=grid[i][col]
        ans=-inf
        for mask in range(n**m2):
            grid3=[[-1 for __ in range(m2)] for ___ in range(n)]
            for col in range(m2):
                shift=mask%n
                for row in range(n):
                    grid3[row][col]=grid2[(shift+row)%n][col]
                mask//=n
            tempAns=0
            for row in range(n):
                maxx=-inf
                for col in range(m2):
                    maxx=max(maxx,grid3[row][col])
                tempAns+=maxx
            ans=max(ans,tempAns)
        allans.append(ans)

    multiLineArrayPrint(allans)

    return

import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]
# def readFloatArr():
#     return [float(x) for x in input().split()]

def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
    dv=defaultValFactory;da=dimensionArr
    if len(da)==1:return [dv() for _ in range(da[0])]
    else:return [makeArr(dv,da[1:]) for _ in range(da[0])]

def queryInteractive(r):
    print('? {}'.format(r))
    sys.stdout.flush()
    return readIntArr()

def answerInteractive(adj,n):
    print('!')
    for u in range(1,n+1):
        for v in adj[u]:
            if v>u:
                print('{} {}'.format(u,v))
    sys.stdout.flush()

inf=float('inf')
MOD=10**9+7
# MOD=998244353

from math import gcd,floor,ceil
# from math import floor,ceil # for Python2

for _abc in range(1):
    main()
```


1228_D. Complete Tripartite

You have a simple undirected graph consisting of n vertices and m edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.

Let's make a definition.

Let v_1 and v_2 be two some nonempty subsets of vertices that do not intersect. Let f(v_{1}, v_{2}) be true if and only if all the conditions are satisfied:

  1. There are no edges with both endpoints in vertex set v_1.
  2. There are no edges with both endpoints in vertex set v_2.
  3. For every two vertices x and y such that x is in v_1 and y is in v_2, there is an edge between x and y.

Create three vertex sets (v_{1}, v_{2}, v_{3}) which satisfy the conditions below;

  1. All vertex sets should not be empty.
  2. Each vertex should be assigned to only one vertex set.
  3. f(v_{1}, v_{2}), f(v_{2}, v_{3}), f(v_{3}, v_{1}) are all true.

Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.

Input

The first line contains two integers n and m (3 ≤ n ≤ 10^{5}, 0 ≤ m ≤ min(3 ⋅ 10^{5}, (n(n-1))/(2))) — the number of vertices and edges in the graph.

The i-th of the next m lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.

Output

If the answer exists, print n integers. i-th integer means the vertex set number (from 1 to 3) of i-th vertex. Otherwise, print -1.

If there are multiple answers, print any.

Examples

Input

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

Output

1 2 2 3 3 3

Input

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

Output

-1

Note

In the first example, if v_{1} = \{ 1 \}, v_{2} = \{ 2, 3 \}, and v_{3} = \{ 4, 5, 6 \} then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well.

<image>

In the second example, it's impossible to make such vertex sets.

```python
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

N,M = inpl()

if M == 0:
    print(-1)
    exit()

cnts = [0]*N
lines = defaultdict(set)
for _ in range(M):
    a,b = inpl()
    a-=1 ; b-=1
    cnts[a] += 1
    cnts[b] += 1
    lines[a].add(b)
    lines[b].add(a)

setc = set(cnts)
L = len(setc)
ans = [-1]*N
if L == 1:
    ans[a] = 1
    ans[b] = 2
    for i in range(N):
        if ans[i] != 0:
            if i not in lines[a]:
                ans[i] = 1
            elif i not in lines[b]:
                ans[i] = 2
            else:
                ans[i] = 3
elif L == 2:
    c1,c2 = list(setc)
    if c1*2 + c2 == N*2:
        i1 = cnts.index(c1)
        i2 = cnts.index(c2)
        for i,c in enumerate(cnts):
            if c == c2:
                ans[i] = 2
            else:
                if i not in lines[i1]:
                    ans[i] = 1
                else:
                    ans[i] = 3
    elif c1 + c2*2 == N*2:
        i1 = cnts.index(c1)
        i2 = cnts.index(c2)
        for i,c in enumerate(cnts):
            if c == c1:
                ans[i] = 1
            else:
                if i not in lines[i2]:
                    ans[i] = 2
                else:
                    ans[i] = 3
    else:
        print(-1)
        exit()
elif L == 3:
    c1,c2,c3 = list(setc)
    for i,c in enumerate(cnts):
        if c == c1:
            ans[i] = 1
        elif c == c2:
            ans[i] = 2
        elif c == c3:
            ans[i] = 3
else:
    print(-1)
    exit()

if len(set(ans)) != 3:
    print(-1)
    exit()

for s in range(N):
    for t in lines[s]:
        if ans[s] == ans[t]:
            print(-1)
            exit()

print(' '.join(map(str,ans)))

```


1270_D. Strange Device

This problem is interactive.

We have hidden an array a of n pairwise different numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon.

This device can answer queries of the following form: in response to the positions of k different elements of the array, it will return the position and value of the m-th among them in the ascending order.

Unfortunately, the instruction for the device was lost during delivery. However, you remember k, but don't remember m. Your task is to find m using queries to this device.

You can ask not more than n queries.

Note that the array a and number m are fixed before the start of the interaction and don't depend on your queries. In other words, interactor is not adaptive.

Note that you don't have to minimize the number of queries, and you don't need to guess array a. You just have to guess m.

Input

The first line contains two integers n and k (1≤ k < n ≤ 500) — the length of the array and the number of the elements in the query.

It is guaranteed that number m satisfies 1≤ m ≤ k, elements a_1, a_2, ..., a_n of the array satisfy 0≤ a_i ≤ 10^9, and all of them are different.

Interaction

You begin the interaction by reading n and k.

To ask a question about elements on positions x_1, x_2, ..., x_k, in a separate line output

? x_1 x_2 x_3 ... x_k

Numbers in the query have to satisfy 1 ≤ x_i ≤ n, and all x_i have to be different. Don't forget to 'flush', to get the answer.

In response, you will receive two integers pos and a_{pos} — the position in the array a of the m-th in ascending order element among a_{x_1}, a_{x_2}, ..., a_{x_k}, and the element on this position.

In case your query is invalid or you asked more than n queries, the program will print -1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.

When you determine m, output

! m

After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:

  * fflush(stdout) or cout.flush() in C++;
  * System.out.flush() in Java;
  * flush(output) in Pascal;
  * stdout.flush() in Python;
  * see documentation for other languages.

Hack format

For the hacks use the following format:

The first line has to contain three integers n, k, m (1 ≤ m ≤ k < n ≤ 500) — the length of the array, number of elements in the query, and which in the ascending order number the device returns.

In the next line output n integers a_1, a_2, ..., a_n (0≤ a_i ≤ 10^9) — the elements of the array. They have to be pairwise different.

Example

Input

4 3
4 9
4 9
4 9
1 2

Output

? 2 3 4
? 1 3 4
? 1 2 4
? 1 2 3
! 3

Note

In the example, n = 4, k = 3, m = 3, a = [2, 0, 1, 9].

```python
import sys
input = sys.stdin.readline

N, K = map(int, input().split())

def inout(A):
    print("?", end=" ")
    print(*A)
    sys.stdout.flush()

    pos, a = map(int, input().split())
    return pos, a

dic = {}
for k in range(1, K+2):
    A = list(range(1,k)) + list(range(k+1, K+2))
    pos, a = inout(A)
    if a in dic:
        dic[a] += 1
    else:
        dic[a] = 1

S =  list(dic.items())
S.sort()
ind = S[1][1]

print("!", ind)
```