1409_B. Minimum Product

You are given four integers a, b, x and y. Initially, a ≥ x and b ≥ y. You can do the following operation no more than n times:

  * Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y.

Your task is to find the minimum possible product of a and b (a ⋅ b) you can achieve by applying the given operation no more than n times.

You have to answer t independent test cases.

Input

The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.

The only line of the test case contains five integers a, b, x, y and n (1 ≤ a, b, x, y, n ≤ 10^9). Additional constraint on the input: a ≥ x and b ≥ y always holds.

Output

For each test case, print one integer: the minimum possible product of a and b (a ⋅ b) you can achieve by applying the given operation no more than n times.

Example

Input

7
10 10 8 5 3
12 8 8 7 2
12343 43 4543 39 123212
1000000000 1000000000 1 1 1
1000000000 1000000000 1 1 1000000000
10 11 2 1 5
10 11 9 1 10

Output

70
77
177177
999999999000000000
999999999
55
10

Note

In the first test case of the example, you need to decrease b three times and obtain 10 ⋅ 7 = 70.

In the second test case of the example, you need to decrease a one time, b one time and obtain 11 ⋅ 7 = 77.

In the sixth test case of the example, you need to decrease a five times and obtain 5 ⋅ 11 = 55.

In the seventh test case of the example, you need to decrease b ten times and obtain 10 ⋅ 1 = 10.

```python
for _ in range(int(input())):
  a,b,x,y,n=map(int,input().split())

  if n>=((a-x)+(b-y)):
    print(x*y)
  else:
    if a>=b and n<=(b-y):
      print(a*(b-n))
    elif b>a and n<=(a-x):
      print((a-n)*b)
    elif n<=(a-x) and n<=(b-y):
      print(min((a-n)*b,a*(b-n)))
    else:

      if n>(a-x):
        qq=x*(b-(n-(a-x)))
      else:
        qq=(a-n)*b

      if n>(b-y):
        qq2=(a-(n-(b-y)))*y
      else:
        qq2=a*(b-n)
      #print(qq,qq2,"pp")
      print(min(qq,qq2))

```


142_E. Help Greg the Dwarf 2

Greg the Dwarf has been really busy recently with excavations by the Neverland Mountain. However for the well-known reasons (as you probably remember he is a very unusual dwarf and he cannot stand sunlight) Greg can only excavate at night. And in the morning he should be in his crypt before the first sun ray strikes. That's why he wants to find the shortest route from the excavation point to his crypt. Greg has recollected how the Codeforces participants successfully solved the problem of transporting his coffin to a crypt. So, in some miraculous way Greg appeared in your bedroom and asks you to help him in a highly persuasive manner. As usual, you didn't feel like turning him down.

After some thought, you formalized the task as follows: as the Neverland mountain has a regular shape and ends with a rather sharp peak, it can be represented as a cone whose base radius equals r and whose height equals h. The graveyard where Greg is busy excavating and his crypt can be represented by two points on the cone's surface. All you've got to do is find the distance between points on the cone's surface.

The task is complicated by the fact that the mountain's base on the ground level and even everything below the mountain has been dug through by gnome (one may wonder whether they've been looking for the same stuff as Greg...). So, one can consider the shortest way to pass not only along the side surface, but also along the cone's base (and in a specific case both points can lie on the cone's base — see the first sample test)

Greg will be satisfied with the problem solution represented as the length of the shortest path between two points — he can find his way pretty well on his own. He gave you two hours to solve the problem and the time is ticking!

Input

The first input line contains space-separated integers r and h (1 ≤ r, h ≤ 1000) — the base radius and the cone height correspondingly. The second and third lines contain coordinates of two points on the cone surface, groups of three space-separated real numbers. The coordinates of the points are given in the systems of coordinates where the origin of coordinates is located in the centre of the cone's base and its rotation axis matches the OZ axis. In this coordinate system the vertex of the cone is located at the point (0, 0, h), the base of the cone is a circle whose center is at the point (0, 0, 0), lying on the XOY plane, and all points on the cone surface have a non-negative coordinate z. It is guaranteed that the distances from the points to the cone surface do not exceed 10 - 12. All real numbers in the input have no more than 16 digits after decimal point.

Output

Print the length of the shortest path between the points given in the input, with absolute or relative error not exceeding 10 - 6.

Examples

Input

2 2
1.0 0.0 0.0
-1.0 0.0 0.0

Output

2.000000000

Input

2 2
1.0 0.0 0.0
1.0 0.0 1.0

Output

2.414213562

Input

2 2
1.0 0.0 1.0
-1.0 0.0 1.0

Output

2.534324263

Input

2 2
1.0 0.0 0.0
0.0 1.0 1.0

Output

3.254470198

```python
import math
mas = list(map(int, input().split()))
r = mas[0]
h = mas[1]
l = (r ** 2 + h ** 2) ** 0.5#2 * math.pi * r
mas = list(map(float, input().split()))
x1 = mas[0]
y1 = mas[1]
z1 = mas[2]
mas = list(map(float, input().split()))
x2 = mas[0]
y2 = mas[1]
z2 = mas[2]
s = 0
if ((z1 == 0) and (z2 == 0)):
    s = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
elif ((z1 != 0) and (z2 != 0)):

    if ((x1 ** 2 + y1 ** 2 == 0) or (x2 ** 2 + y2 ** 2 == 0)):
        alf = 0
    else:
        alf = math.acos((x1 * x2 + y1 * y2) / math.sqrt((x1 ** 2 + y1 ** 2) * (x2 ** 2 + y2 ** 2)))

    l1 = l * (1 - z1 / h)
    l2 = l * (1 - z2 / h)
    xx1 = l1; yy1 = 0;
    xx1_ = l1 * math.cos(2 * math.pi * r / l); yy1_ = l1 * math.sin(2 * math.pi * r / l);
    phi = alf * r / l
    xx2 = l2 * math.cos(phi); yy2 = l2 * math.sin(phi)
    # расстояние только по боковой поверхности
    sbok = min(((xx1 - xx2) ** 2 + (yy1 - yy2) ** 2) ** 0.5, ((xx1_ - xx2) ** 2 + (yy1_ - yy2) ** 2) ** 0.5)
    #print(sbok)
    # расстояние через основание
    step1 = 2 * math.pi
    step2 = 2 * math.pi
    start1 = 0
    start2 = 0
    smin = 1000000000000000
    sbok1min = 0
    sbok2min = 0
    sosnmin = 0
    alf1min = 0
    alf2min = 0
    phi1min = 0
    phi2min = 0
    i1min = 0
    i2min = 0
    for j in range(20):
        k = 80
        i1 = 0
        for i1 in range(k + 1):
            alf1 = start1 + i1 / k * step1
            phi1 = alf1 * r / l
            xxx1 = l * math.cos(phi1)
            yyy1 = l * math.sin(phi1)
            xxx1_ = r * math.cos(alf1)
            yyy1_ = r * math.sin(alf1)
            i2 = 0
            for i2 in range(k + 1):
                alf2 = start2 + i2 / k * step2
                phi2 = alf2 * r / l
                xxx2 = l * math.cos(phi2)
                yyy2 = l * math.sin(phi2)
                xxx2_ = r * math.cos(alf2)
                yyy2_ = r * math.sin(alf2)
                sbok1 = (min((xx1 - xxx1) ** 2 + (yy1 - yyy1) ** 2, (xx1_ - xxx1) ** 2 + (yy1_ - yyy1) ** 2)) ** 0.5
                sbok2 = ((xx2 - xxx2) ** 2 + (yy2 - yyy2) ** 2) ** 0.5
                sosn = ((xxx1_ - xxx2_) ** 2 + (yyy1_ - yyy2_) ** 2) ** 0.5
                ss = sbok1 + sbok2 + sosn
                if (ss < smin):
                    smin = ss
                    alf1min = alf1
                    start1min = alf1min - step1 / k
                    i1min = i1
                    alf2min = alf2
                    start2min = alf2min - step2 / k
                    i2min = i2
                    sbok1min = sbok1
                    sbok2min = sbok2
                    sosnmin = sosn
                    phi1min = phi1
                    phi2min = phi2
        step1 = step1 / k * 2
        start1 = start1min
        if (start1 < 0):
            start1 = 0
        step2 = step2 / k * 2
        start2 = start2min
        if (start2 < 0):
            start2 = 0

    #print(smin, alf1min, alf2min, phi1min, phi2min, phi)
    #print(sbok1min, sbok2min, sosnmin)
    s = min(sbok, smin)
else:
    if (z1 == 0):
        xtemp = x2
        ytemp = y2
        ztemp = z2
        x2 = x1
        y2 = y1
        z2 = z1
        x1 = xtemp
        y1 = ytemp
        z1 = ztemp
    if ((x1 ** 2 + y1 ** 2 == 0) or (x2 ** 2 + y2 ** 2 == 0)):
        alf = 0
    else:
        alf = math.acos((x1 * x2 + y1 * y2) / math.sqrt((x1 ** 2 + y1 ** 2) * (x2 ** 2 + y2 ** 2)))
    l1 = l * (1 - z1 / h)
    xx1 = l1; yy1 = 0;
    xx1_ = l1 * math.cos(2 * math.pi * r / l); yy1_ = l1 * math.sin(2 * math.pi * r / l);
    step1 = 2 * math.pi
    start1 = 0
    smin = 1000000000000000
    sbok1min = 0
    alf1min = 0
    phi1min = 0
    i1min = 0
    for j in range(30):
        k = 1000
        i1 = 0
        for i1 in range(k + 1):
            alf1 = start1 + i1 / k * step1
            phi1 = alf1 * r / l
            xxx1 = l * math.cos(phi1)
            yyy1 = l * math.sin(phi1)
            xxx1_ = r * math.cos(alf1)
            yyy1_ = r * math.sin(alf1)
            sbok1 = (min((xx1 - xxx1) ** 2 + (yy1 - yyy1) ** 2, (xx1_ - xxx1) ** 2 + (yy1_ - yyy1) ** 2)) ** 0.5
            rosn = (x2 ** 2 + y2 ** 2) ** 0.5
            xosn = rosn * math.cos(alf)
            yosn = rosn * math.sin(alf)
            sosn = ((xxx1_ - xosn) ** 2 + (yyy1_ - yosn) ** 2) ** 0.5
            ss = sbok1 + sosn
            if (ss < smin):
                smin = ss
                alf1min = alf1
                start1min = alf1min - step1 / k
                i1min = i1
                sbok1min = sbok1
                sosnmin = sosn
                phi1min = phi1
        step1 = step1 / k * 2
        start1 = start1min
        if (start1 < 0):
            start1 = 0
    s = smin

print(s)

```


1453_B. Suffix Operations

Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:

  1. Increase all elements of a suffix of the array by 1.
  2. Decrease all elements of a suffix of the array by 1.

A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.

Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?

Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.

Input

Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).

Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.

The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).

It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.

Output

For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.

Example

Input

7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447

Output

0
1
3
4
6
5
2847372102

Note

In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.

In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.

In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:

  * Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
  * Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].

In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:

  * Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
  * Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].

```python
T = int(input())
for _ in range(T):
    N = int(input())
    A = list(map(int,input().split()))
    d = sum(abs(a-b) for a,b in zip(A,A[1:]))
    ans = d
    for a,b,c in zip(A,A[1:],A[2:]):
        p = abs(a-b) + abs(b-c)
        q = abs(a-c)
        ans = min(ans, d - (p-q))
    ans = min(ans, d - abs(A[0] - A[1]), d - abs(A[-1] - A[-2]))
    print(ans)

```


1503_D. Flip the Cards

There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.

A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≤ i<n.

To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?

Input

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

The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≤ a_i, b_i≤ 2n). Every integer between 1 and 2n appears exactly once.

Output

If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.

Examples

Input

5
3 10
6 4
1 9
5 8
2 7

Output

2

Input

2
1 2
3 4

Output

-1

Input

3
1 2
3 6
4 5

Output

-1

Note

In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.

In the second test case, it is impossible to sort the deck.

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

n = int(input())

front = [-1] * n
back = [-1] * n
rev = [-1] * (2 * n)
used = [False] * n
opp = [-1] * (2 * n)

for c in range(n):
    a, b = map(lambda x: int(x) - 1, input().split())
    front[c] = a
    back[c] = b
    rev[a] = c
    rev[b] = c
    opp[a] = b
    opp[b] = a

left = -1
right = 2 * n
out = 0
works = True
while right - left > 1:
    s_l = left + 1
    s_r = right
    curr = 0
    curr_f = 0

    while (s_l > left or s_r < right) and right - left > 1:
        #print(left, s_l, s_r, right)
        if s_l > left:
            left += 1
            card = rev[left]
            if not used[card]:
                used[card] = True
                curr += 1
                if front[card] == left:
                    curr_f += 1
                if opp[left] < s_r:
                    s_r = opp[left]
                else:
                    works = False
        elif s_r < right:
            right -= 1
            card = rev[right]
            if not used[card]:
                used[card] = True
                curr += 1
                if front[card] == right:
                    curr_f += 1
                if opp[right] > s_l:
                    s_l = opp[right]
                else:
                    works = False
    if s_l > s_r:
        works = False
    if not works:
        break
    out += min(curr_f, curr - curr_f)

if works:
    print(out)
else:
    print(-1)

```


1527_B2. Palindrome Game (hard version)

The only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.

A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.

Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.

In each turn, the player can perform one of the following operations:

  1. Choose any i (1 ≤ i ≤ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
  2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.

Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.

The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.

Input

The first line contains a single integer t (1 ≤ t ≤ 10^3). Then t test cases follow.

The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3).

The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.

Note that there is no limit on the sum of n over test cases.

Output

For each test case print a single word in a new line:

  * "ALICE", if Alice will win the game,
  * "BOB", if Bob will win the game,
  * "DRAW", if the game ends in a draw.

Example

Input

3
3
110
2
00
4
1010

Output

ALICE
BOB
ALICE

Note

In the first test case of example,

  * in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
  * in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.

Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.

In the second test case of example,

  * in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
  * in the 2-nd move Bob reverses the string.
  * in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.

Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.

```python
# from __future__ import print_function,division
# range = xrange
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(10**9)
from sys import stdin, stdout
from collections import defaultdict, Counter
M = 10**9+7

def main():
    for _ in range(int(input())):
        n = int(input())
        s = input().strip()
        w = 0
        os = 0
        mid = 0
        for i in range(n//2):
            if s[i]!=s[n-i-1]:
                w+=1
            elif s[i]=="0":
                os+=2
        if n%2 and s[n//2]=='0':
            mid = 1
        if w==0:
            if mid==1 and os==0:
                print("BOB")
            elif mid==1:
                print("ALICE")
            else:
                print("BOB")
        elif w==1:
            if mid==1:
                if os==0:
                    print("DRAW")
                else:
                    print("ALICE")
            else:
                print("ALICE")
        else:
            print("ALICE")

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


159_A. Friends or Not

Polycarpus has a hobby — he develops an unusual social network. His work is almost completed, and there is only one more module to implement — the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that user A sent user B a message at time t1, and user B sent user A a message at time t2. If 0 < t2 - t1 ≤ d, then user B's message was an answer to user A's one. Users A and B are considered to be friends if A answered at least one B's message or B answered at least one A's message.

You are given the log of messages in chronological order and a number d. Find all pairs of users who will be considered to be friends.

Input

The first line of the input contains two integers n and d (1 ≤ n, d ≤ 1000). The next n lines contain the messages log. The i-th line contains one line of the log formatted as "Ai Bi ti" (without the quotes), which means that user Ai sent a message to user Bi at time ti (1 ≤ i ≤ n). Ai and Bi are non-empty strings at most 20 characters long, consisting of lowercase letters ('a' ... 'z'), and ti is an integer (0 ≤ ti ≤ 10000). It is guaranteed that the lines are given in non-decreasing order of ti's and that no user sent a message to himself. The elements in the lines are separated by single spaces.

Output

In the first line print integer k — the number of pairs of friends. In the next k lines print pairs of friends as "Ai Bi" (without the quotes). You can print users in pairs and the pairs themselves in any order. Each pair must be printed exactly once.

Examples

Input

4 1
vasya petya 1
petya vasya 2
anya ivan 2
ivan anya 4

Output

1
petya vasya

Input

1 1000
a b 0

Output

0

Note

In the first sample test case Vasya and Petya are friends because their messages' sending times are one second apart. Anya and Ivan are not, because their messages' sending times differ by more than one second.

```python
import re
from collections import Counter

class Task:
    data = []
    delta = 0
    friends = set()

    def getData(self):
        n, self.delta = [int(x) for x in input().split(" ")]
        for i in range(0, n):
            self.data += [input()]

    def solve(self):
        messages = dict()
        for line1 in self.data:
            A1, B1, time1 = line1.split(" ")
            for line2 in self.data:
                A2, B2, time2 = line2.split(" ")
                if A2 == B1 and B2 == A1 and \
                        0 < abs(int(time2) - int(time1)) <= self.delta:
                    self.friends.add(min(A2 + " " + B2, B2 + " " + A2))

    def printAnswer(self):
        print(len(self.friends))
        for pair in self.friends:
            print(pair)

task = Task();
task.getData();
task.solve();
task.printAnswer();

```


178_D2. Magic Squares

The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.

The magic square is a matrix of size n × n. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number s. The sum of numbers in each column of the matrix is also equal to s. In addition, the sum of the elements on the main diagonal is equal to s and the sum of elements on the secondary diagonal is equal to s. Examples of magic squares are given in the following figure:

<image> Magic squares

You are given a set of n2 integers ai. It is required to place these numbers into a square matrix of size n × n so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.

It is guaranteed that a solution exists!

Input

The first input line contains a single integer n. The next line contains n2 integers ai ( - 108 ≤ ai ≤ 108), separated by single spaces.

The input limitations for getting 20 points are:

  * 1 ≤ n ≤ 3

The input limitations for getting 50 points are:

  * 1 ≤ n ≤ 4
  * It is guaranteed that there are no more than 9 distinct numbers among ai.

The input limitations for getting 100 points are:

  * 1 ≤ n ≤ 4

Output

The first line of the output should contain a single integer s. In each of the following n lines print n integers, separated by spaces and describing the resulting magic square. In the resulting magic square the sums in the rows, columns and diagonals must be equal to s. If there are multiple solutions, you are allowed to print any of them.

Examples

Input

3
1 2 3 4 5 6 7 8 9

Output

15
2 7 6
9 5 1
4 3 8

Input

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

Output

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

Input

2
5 5 5 5

Output

10
5 5
5 5

```python
import sys, random
def f(b):
    global a
    a = [[0] * n for o in range(n)]

    for i in range(n):
        for j in range(n):
            a[i][j] = b[i * n + j]

    rez = 0
    for i in range(n):
        ns = 0
        for j in range(n):
            ns += a[i][j]
        rez += abs(su - ns)

    for j in range(n):
        ns = 0
        for i in range(n):
            ns += a[i][j]
        rez += abs(su - ns)
    ns = 0
    for i in range(n):
        ns += a[i][i]
    rez += abs(su - ns)
    ns = 0
    for i in range(n):
        ns += a[i][n - i - 1]
    rez += abs(su - ns)
    return rez

input = sys.stdin.readline
n = int(input())
d = list(map(int, input().split()))
su = sum(d) // n
p = f(d)
while p:
    random.shuffle(d)
    p = f(d)
    for k in range(1000):

        i = random.randint(0, n*n-1)
        j = random.randint(0, n*n-1)
        while i == j:
            j = random.randint(0, n*n-1)
        if i > j:
            i, j = j, i
        d[i], d[j] = d[j], d[i]
        q = f(d)
        if q < p:
            p = q
        else:
            d[i], d[j] = d[j], d[i]
        p = f(d)
print(su)
for i in a:
    print(*i)

```


200_D. Programming Language

Recently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, default values).

Valery decided to examine template procedures in this language in more detail. The description of a template procedure consists of the procedure name and the list of its parameter types. The generic type T parameters can be used as parameters of template procedures.

A procedure call consists of a procedure name and a list of variable parameters. Let's call a procedure suitable for this call if the following conditions are fulfilled:

  * its name equals to the name of the called procedure;
  * the number of its parameters equals to the number of parameters of the procedure call;
  * the types of variables in the procedure call match the corresponding types of its parameters. The variable type matches the type of a parameter if the parameter has a generic type T or the type of the variable and the parameter are the same.

You are given a description of some set of template procedures. You are also given a list of variables used in the program, as well as direct procedure calls that use the described variables. For each call you need to count the number of procedures that are suitable for this call.

Input

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of template procedures. The next n lines contain the description of the procedures specified in the following format:

"void procedureName (type_1, type_2, ..., type_t)" (1 ≤ t ≤ 5), where void is the keyword, procedureName is the procedure name, type_i is the type of the next parameter. Types of language parameters can be "int", "string", "double", and the keyword "T", which denotes the generic type.

The next line contains a single integer m (1 ≤ m ≤ 1000) — the number of used variables. Next m lines specify the description of the variables in the following format:

"type variableName", where type is the type of variable that can take values "int", "string", "double", variableName — the name of the variable.

The next line contains a single integer k (1 ≤ k ≤ 1000) — the number of procedure calls. Next k lines specify the procedure calls in the following format:

"procedureName (var_1, var_2, ..., var_t)" (1 ≤ t ≤ 5), where procedureName is the name of the procedure, var_i is the name of a variable.

The lines describing the variables, template procedures and their calls may contain spaces at the beginning of the line and at the end of the line, before and after the brackets and commas. Spaces may be before and after keyword void. The length of each input line does not exceed 100 characters. The names of variables and procedures are non-empty strings of lowercase English letters and numbers with lengths of not more than 10 characters. Note that this is the only condition at the names. Only the specified variables are used in procedure calls. The names of the variables are distinct. No two procedures are the same. Two procedures are the same, if they have identical names and identical ordered sets of types of their parameters.

Output

On each of k lines print a single number, where the i-th number stands for the number of suitable template procedures for the i-th call.

Examples

Input

4
void f(int,T)
void  f(T, T)
 void foo123   ( int,  double,  string,string  )
  void  p(T,double)
3
int a
 string    s
double x123
5
f(a,  a)
  f(s,a   )
foo   (a,s,s)
 f  (  s  ,x123)
proc(a)

Output

2
1
0
1
0

Input

6
void f(string,double,int)
void f(int)
   void f  ( T  )
void procedure(int,double)
void f  (T, double,int)
void f(string, T,T)
4
 int a
 int x
string  t
double  val
5
f(t, a, a)
f(t,val,a)
f(val,a, val)
 solve300(val, val)
f  (x)

Output

1
3
0
0
2

```python
def main():
    from collections import defaultdict
    import sys

    strings = sys.stdin.read().split('\n')
    strings.reverse()

    f = defaultdict(lambda: defaultdict(int))
    n = int(strings.pop())

    for i in range(n):
        s = strings.pop().replace('(', ' ').replace(')', ' ').replace(',', ' ')
        _, name, *args = s.split()
        f[name][tuple(args)] += 1

    m = int(strings.pop())
    variables = dict(reversed(strings.pop().split()) for j in range(m))

    result = []
    k = int(strings.pop())
    for i in range(k):
        s = strings.pop().replace('(', ' ').replace(')', ' ').replace(',', ' ')
        name, *args = s.split()

        count = 0
        args = [variables[i] for i in args]
        N = len(args)
        for mask in range(1 << N):
            tmp = tuple('T' if mask & (1 << i) else args[i] for i in range(N))
            count += f[name][tmp]
        result.append(str(count))

    print('\n'.join(result))

main()

```


225_C. Barcode

You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.

A picture is a barcode if the following conditions are fulfilled:

  * All pixels in each column are of the same color.
  * The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y.

Input

The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y).

Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#".

Output

In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists.

Examples

Input

6 5 1 2
##.#.
.###.
###..
#...#
.##.#
###..

Output

11

Input

2 5 1 1
#####
.....

Output

5

Note

In the first test sample the picture after changing some colors can looks as follows:

    .##..
    .##..
    .##..
    .##..
    .##..
    .##..

In the second test sample the picture after changing some colors can looks as follows:

    .#.#.
    .#.#.

```python
def main():
    n, m, x, y = map(int, input().split())

    col = [0] * m
    for i in range(n):
        row = input()
        for j in range(m):
            if row[j] == '.':
                col[j] += 1

    acc = [0]
    for j in range(m):
        acc.append(acc[-1] + col[j])

    dp = [[0]*(m+1), [0]*(m+1)]

    for j in range(1, m+1):
        dp[0][j] = float('infinity')
        dp[1][j] = float('infinity')
        for k in range(x, y+1):
            if j-k >= 0:
                wp = acc[j] - acc[j-k]
                bp = k * n - wp
                dp[0][j] = min(dp[0][j], dp[1][j-k] + wp)
                dp[1][j] = min(dp[1][j], dp[0][j-k] + bp)

    print(min(dp[0][m], dp[1][m]))

if __name__ == "__main__":
    main()

```


24_A. Ring road

Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?

Input

The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.

Output

Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.

Examples

Input

3
1 3 1
1 2 1
3 2 1

Output

1

Input

3
1 3 1
1 2 5
3 2 1

Output

2

Input

6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42

Output

39

Input

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

Output

0

```python
n = int(input())
g=[]
d=[]
cost=[]
for i in range(n+1):
	g.append([])
	d.append([])
	for j in range(n+1):
		g[i].append(0)
		d[i].append(0)

x,y=[],[]

for i in range(n):
	a,b,c = tuple([int(x) for x in input().split()])
	g[a][b]=c
	g[b][a]=c
	d[a][b]=c
	d[b][a]=-c

ans = 0
tot=0
stack=[1]
visited=[1]

while stack!=[]:
	t = stack.pop()
	for i in range(1,n+1):
		if i not in visited and g[t][i]>0:
			stack.append(i)
			visited.append(i)
			tot+=g[t][i]
			if d[t][i]<0:
				ans+=-d[t][i]
			break
if d[visited[-1]][1]<0:
	ans+=-d[visited[-1]][1]
tot+=g[visited[-1]][1]
visited.append(1)
if ans>tot-ans:
	ans=tot-ans
print(ans)

```


274_B. Zero Tree

A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.

A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.

You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation:

  1. Select the subtree of the given tree that includes the vertex with number 1.
  2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree.

Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.

Input

The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree.

The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109).

Output

Print the minimum number of operations needed to solve the task.

Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Examples

Input

3
1 2
1 3
1 -1 1

Output

3

```python
n = int(input())
r = [[] for i in range(n + 1)]
r[1] = [0]
for i in range(n - 1):
    a, b = map(int, input().split())
    r[a].append(b)
    r[b].append(a)
t = list(map(int, input().split()))
u, v = [0] * (n + 1), [0] * (n + 1)
for i, j in enumerate(t, 1):
    if j < 0: u[i] = - j
    else: v[i] = j
# print(u,v)
t, p = [1], [0] * (n + 1)
while t:
    a = t.pop()
    for b in r[a]:
        if p[b]: continue
        p[b] = a
        t.append(b)
k = [len(t) for t in r]
t = [a for a in range(2, n + 1) if k[a] == 1]
x, y = [0] * (n + 1), [0] * (n + 1)
while t:
    a = t.pop()
    b = p[a]
    x[b] = max(x[b], u[a])
    y[b] = max(y[b], v[a])
    k[b] -= 1
    if k[b] == 1:
        t.append(b)
        if u[b] > 0:
            if x[b] - y[b] > u[b]:
                u[b], v[b] = x[b], x[b] - u[b]
            else: u[b], v[b] = y[b] + u[b], y[b]
        else:
            if y[b] - x[b] > v[b]:
                u[b], v[b] = y[b] - v[b], y[b]
            else: u[b], v[b] = x[b], x[b] + v[b]
print(u[1] + v[1])
```


320_B. Ping-Pong (Easy Version)

In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2.

Your program should handle the queries of the following two types:

  1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals.
  2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval?

Answer all the queries. Note, that initially you have an empty set of intervals.

Input

The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value.

It's guaranteed that all queries are correct.

Output

For each query of the second type print "YES" or "NO" on a separate line depending on the answer.

Examples

Input

5
1 1 5
1 5 11
2 1 2
1 2 9
2 1 2

Output

NO
YES

```python
def main():
    intervals = []
    visited = []
    for _ in range(int(input())):
        read_input(intervals, visited)

def read_input(intervals: list, visited: list) -> None:
    command, x, y = [int(x) for x in input().split(" ")]

    if (command == 1):
        intervals.append((x, y))
        visited.append(False)
    else:
        # reset the visited array
        for idx in range(len(visited)):
            visited[idx] = False

        if(find_path(intervals, visited, x-1, y-1)):
            print("YES")
        else:
            print("NO")

def find_path(intervals: list, visited: list, start: int, end: int) -> bool:

    if (start == end):
        return True
    else:
        for x in range(len(intervals)):
            if (can_move(intervals[start], intervals[x]) and not visited[x]):
                visited[x] = True
                if(find_path(intervals, visited, x, end)):
                    return True

    return False

def can_move(a: tuple, b: tuple) -> bool:
    if (b[0] < a[0] < b[1]):
        return True
    elif (b[0] < a[1] < b[1]):
        return True
    else:
        return False

if __name__ == "__main__":
    main()

```


368_D. Sereja ans Anagrams

Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.

Sereja needs to rush to the gym, so he asked to find all the described positions of q.

Input

The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).

Output

In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.

Examples

Input

5 3 1
1 2 3 2 1
1 2 3

Output

2
1 3

Input

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

Output

2
1 2

```python
from sys import stdin, stdout
from math import log, sqrt
lines = stdin.readlines()
n = int(lines[0].split()[0])
m = int(lines[0].split()[1])
p = int(lines[0].split()[2])
a = [int(x) for x in lines[1].split()]
b = [int(x) for x in lines[2].split()]

hash_map = {}
def hash_elem(elem):
    if hash_map.get(elem, -1) == -1:
        if elem < 1000:
            hash_map[elem] = elem//2 + elem * 1134234546677 + int(elem/3) + int(elem**2) + elem<<2 + elem>>7 + int(log(elem)) + int(sqrt(elem))  + elem&213213 + elem^324234211323 + elem|21319423094023
        else:
            hash_map[elem] = 3 + elem^34# elem<<2 + elem>>7 + elem&243 + elem^324 + elem|434
    return elem + hash_map[elem]

c = [hash_elem(elem) for elem in a]

c_new = [sum([c[q + p*i] for i in range(m)]) for q in range(min(p, max(0,n - (m-1)*p)))]
for q in range(p,n - (m-1)*p):
    prev = c_new[q - p]
    c_new.append(prev - c[q - p] + c[q + p*(m-1)])

b_check = sum([hash_elem(elem) for elem in b])

ans1 = 0
ans = []
for q in range(n - (m-1)*p):
    c_check = c_new[q]
    if b_check != c_check:
        continue
    else:
        ans1 += 1
        ans.append(q+1)

print(ans1)
stdout.write(' '.join([str(x) for x in ans]))

```


412_D. Giving Awards

The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.

Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person x to his office for a reward, and then immediately invite person y, who has lent some money to person x, then they can meet. Of course, in such a situation, the joy of person x from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.

However, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.

Input

The first line contains space-separated integers n and m <image> — the number of employees in R1 and the number of debt relations. Each of the following m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi), these integers indicate that the person number ai owes money to a person a number bi. Assume that all the employees are numbered from 1 to n.

It is guaranteed that each pair of people p, q is mentioned in the input data at most once. In particular, the input data will not contain pairs p, q and q, p simultaneously.

Output

Print -1 if the described order does not exist. Otherwise, print the permutation of n distinct integers. The first number should denote the number of the person who goes to the CEO office first, the second number denote the person who goes second and so on.

If there are multiple correct orders, you are allowed to print any of them.

Examples

Input

2 1
1 2

Output

2 1

Input

3 3
1 2
2 3
3 1

Output

2 1 3

```python
n,m = map(int,input().split())
g = [set() for i in range(n)]
for i in range(m):
    a,b = map(int,input().split())
    g[a-1].add(b-1)
c = [0]*n
for i in range(n):
    c[i]=i
for i in range(n):
    j=i
    while j>0 and c[j] in g[c[j-1]]:
        c[j],c[j-1]=c[j-1],c[j]
        j-=1
for i in c:
    print(i+1,end=' ')
```


43_A. Football

One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.

Input

The first line contains an integer n (1 ≤ n ≤ 100) — the number of lines in the description. Then follow n lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.

Output

Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.

Examples

Input

1
ABC

Output

ABC

Input

5
A
ABA
ABA
A
A

Output

A

```python
n=int(input())
a,b=input(),""
x,y=1,0
for i in range(n-1):
    s=input()
    if a==s:
        x+=1
    else:
        b=s
        y+=1
print([b,a][x>y])
```


461_C. Appleman and a Sheet of Paper

Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types:

  1. Fold the sheet of paper at position pi. After this query the leftmost part of the paper with dimensions 1 × pi must be above the rightmost part of the paper with dimensions 1 × ([current width of sheet] - pi).
  2. Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance li from the left border of the current sheet of paper and the other at distance ri from the left border of the current sheet of paper.

Please look at the explanation of the first test example for better understanding of the problem.

Input

The first line contains two integers: n and q (1 ≤ n ≤ 105; 1 ≤ q ≤ 105) — the width of the paper and the number of queries.

Each of the following q lines contains one of the described queries in the following format:

  * "1 pi" (1 ≤ pi < [current width of sheet]) — the first type query.
  * "2 li ri" (0 ≤ li < ri ≤ [current width of sheet]) — the second type query.

Output

For each query of the second type, output the answer.

Examples

Input

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

Output

4
3

Input

10 9
2 2 9
1 1
2 0 1
1 8
2 0 8
1 2
2 1 3
1 4
2 2 4

Output

7
2
10
4
5

Note

The pictures below show the shapes of the paper during the queries of the first example:

<image>

After the first fold operation the sheet has width equal to 4, after the second one the width of the sheet equals to 2.

```python
from itertools import starmap

def main():
    n, q = map(int, input().split())

    a = list(range(n + 1))
    flipped = False
    start = 0
    end = n

    for _ in range(q):
        cmd, *args = map(int, input().split())

        if cmd == 1:
            p = args[0]
            if p > end-start-p:
                flipped = not flipped
                p = end-start-p
            if flipped:
                a[end-p:end-2*p:-1] = starmap(
                    lambda a, b: a+n-b,
                    zip(a[end-p:end-2*p:-1], a[end-p:end])
                )
                end -= p
            else:
                start += p
                a[start:start+p] = starmap(
                    lambda a, b: a-b,
                    zip(a[start:start+p], a[start:start-p:-1])
                )
        else:
            l, r = args
            if flipped:
                l, r = end-start-r, end-start-l
            print(a[start + r] - a[start + l])

if __name__ == '__main__':
    main()

```


485_B. Valuable Resources

Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems.

Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. The map contains mines with valuable resources, located at some points with integer coordinates. The sizes of mines are relatively small, i.e. they can be treated as points. The city should be built in such a way that all the mines are inside or on the border of the city square.

Building a city takes large amount of money depending on the size of the city, so you have to build the city with the minimum area. Given the positions of the mines find the minimum possible area of the city.

Input

The first line of the input contains number n — the number of mines on the map (2 ≤ n ≤ 1000). Each of the next n lines contains a pair of integers xi and yi — the coordinates of the corresponding mine ( - 109 ≤ xi, yi ≤ 109). All points are pairwise distinct.

Output

Print the minimum area of the city that can cover all the mines with valuable resources.

Examples

Input

2
0 0
2 2

Output

4

Input

2
0 0
0 3

Output

9

```python
# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
mx = -10 ** 10
mix = 10 ** 10
my = mx
miy = mix
for _ in range(int(input())):
    a, b = map(int, input().split())
    mx = max(mx, a)
    mix = min(mix, a)
    my = max(my, b)
    miy = min(miy, b)
ans = max(mx - mix, my - miy)
print(ans * ans)

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

```


509_B. Painting Pebbles

There are n piles of pebbles on the table, the i-th pile contains ai pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.

In other words, let's say that bi, c is the number of pebbles of color c in the i-th pile. Then for any 1 ≤ c ≤ k, 1 ≤ i, j ≤ n the following condition must be satisfied |bi, c - bj, c| ≤ 1. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then bi, c is considered to be zero.

Input

The first line of the input contains positive integers n and k (1 ≤ n, k ≤ 100), separated by a space — the number of piles and the number of colors respectively.

The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) denoting number of pebbles in each of the piles.

Output

If there is no way to paint the pebbles satisfying the given condition, output "NO" (without quotes) .

Otherwise in the first line output "YES" (without quotes). Then n lines should follow, the i-th of them should contain ai space-separated integers. j-th (1 ≤ j ≤ ai) of these integers should be equal to the color of the j-th pebble in the i-th pile. If there are several possible answers, you may output any of them.

Examples

Input

4 4
1 2 3 4

Output

YES
1
1 4
1 2 4
1 2 3 4

Input

5 2
3 2 4 1 3

Output

NO

Input

5 4
3 2 4 3 5

Output

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

```python
import sys,math,bisect
from random import randint
inf = float('inf')
mod = 998244353
"========================================"
def lcm(a,b):
    return int((a/math.gcd(a,b))*b)
def gcd(a,b):
    return int(math.gcd(a,b))
def tobinary(n):
    return bin(n)[2:]
def binarySearch(a,x):
    i = bisect.bisect_left(a,x)
    if i!=len(a) and a[i]==x:
        return i
    else:
        return -1
def lowerBound(a, x):
    i = bisect.bisect_left(a, x)
    if i:
        return (i-1)
    else:
        return -1
def upperBound(a,x):
    i = bisect.bisect_right(a,x)
    if i!= len(a)+1 and a[i-1]==x:
        return (i-1)
    else:
        return -1
def primesInRange(n):
    ans = []
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    for p in range(2, n+1):
        if prime[p]:
            ans.append(p)
    return ans
def primeFactors(n):
    factors = []
    while n % 2 == 0:
        factors.append(2)
        n = n // 2
    for i in range(3,int(math.sqrt(n))+1,2):
        while n % i== 0:
            factors.append(i)
            n = n // i
    if n > 2:
        factors.append(n)
    return factors
def isPrime(n,k=5):
    if (n <2):
        return True
    for i in range(0,k):
        a = randint(1,n-1)
        if(pow(a,n-1,n)!=1):
            return False
    return True
"========================================="
"""
n = int(input())
n,k = map(int,input().split())
arr = list(map(int,input().split()))
"""
from collections import deque,defaultdict,Counter
import heapq,string

n,k = map(int,input().split())
arr = list(map(int,input().split()))
if max(arr)-min(arr)>k:
    print('NO')
else:
    ans = [[0]*i for i in arr]
    c=min(arr)
    k=1
    for i in range(n):
        for j in range(min(arr)):
            ans[i][j]=1
    while c<max(arr):
        for i in range(n):
            if len(ans[i]) > c:
                ans[i][c]=k
        c+=1
        k+=1
    print('YES')
    for i in ans:
        print(*i)

```


558_C. Amr and Chemistry

Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.

Amr has n different types of chemicals. Each chemical i has an initial volume of ai liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.

To do this, Amr can do two different kind of operations.

  * Choose some chemical i and double its current volume so the new volume will be 2ai
  * Choose some chemical i and divide its volume by two (integer division) so the new volume will be <image>

Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?

Input

The first line contains one number n (1 ≤ n ≤ 105), the number of chemicals.

The second line contains n space separated integers ai (1 ≤ ai ≤ 105), representing the initial volume of the i-th chemical in liters.

Output

Output one integer the minimum number of operations required to make all the chemicals volumes equal.

Examples

Input

3
4 8 2

Output

2

Input

3
3 5 6

Output

5

Note

In the first sample test, the optimal solution is to divide the second chemical volume by two, and multiply the third chemical volume by two to make all the volumes equal 4.

In the second sample test, the optimal solution is to divide the first chemical volume by two, and divide the second and the third chemical volumes by two twice to make all the volumes equal 1.

```python
from collections import Counter

def main():
    input()
    aa = list(map(int, input().split()))
    le, l = max(aa).bit_length(), []
    for i, a in enumerate(aa):
        j = le - a.bit_length()
        aa[i] = a << j
        l.append(j)
    mi, ma = min(aa), max(aa)
    a = mask = (1 << le) - 1
    if mi == ma:
        while mi == mi & a:
            mask = a
            a &= a << 1
    else:
        while mi != ma or not (mi & 1):
            mask &= mask << 1
            mi >>= 1
            ma >>= 1
    mask ^= (1 << le) - 1
    le, cnt = mask.bit_length(), Counter()
    for a, i in zip(aa, l):
        a &= mask
        if a:
            a = a.bit_length()
        cnt[i, a] += 1
    res = [0] * (le + 1)
    for (i, a), c in cnt.items():
        if a:
            base, baseidx = (a - i) * c, le - a
        else:
            base, baseidx = 0, le - i
        j = base
        for i in range(baseidx - 1, -1, -1):
            j += c
            res[i] += j
        j = base
        for i in range(baseidx, le + 1):
            res[i] += j
            j += c
    print(min(res))

if __name__ == '__main__':
    main()

```


584_A. Olesya and Rodion

Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.

Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print  - 1.

Input

The single line contains two numbers, n and t (1 ≤ n ≤ 100, 2 ≤ t ≤ 10) — the length of the number and the number it should be divisible by.

Output

Print one such positive number without leading zeroes, — the answer to the problem, or  - 1, if such number doesn't exist. If there are multiple possible answers, you are allowed to print any of them.

Examples

Input

3 2

Output

712

```python
n, t = input().split(' ')

n = int(n)
t = int(t)

a = 10 ** (n-1)
b = 10 ** (n)

for i in range(a, b):
    if i == b-1:
        if i%t ==0:
            print(i)
            break
        else:
            print(-1)
            break
    else:
        if i%t == 0:
            print(i)
            break

    i = i + 1

```


606_A. Magic Spheres

Carl is a beginner magician. He has a blue, b violet and c orange magic spheres. In one move he can transform two spheres of the same color into one sphere of any other color. To make a spell that has never been seen before, he needs at least x blue, y violet and z orange spheres. Can he get them (possible, in multiple actions)?

Input

The first line of the input contains three integers a, b and c (0 ≤ a, b, c ≤ 1 000 000) — the number of blue, violet and orange spheres that are in the magician's disposal.

The second line of the input contains three integers, x, y and z (0 ≤ x, y, z ≤ 1 000 000) — the number of blue, violet and orange spheres that he needs to get.

Output

If the wizard is able to obtain the required numbers of spheres, print "Yes". Otherwise, print "No".

Examples

Input

4 4 0
2 1 2

Output

Yes

Input

5 6 1
2 7 2

Output

No

Input

3 3 3
2 2 2

Output

Yes

Note

In the first sample the wizard has 4 blue and 4 violet spheres. In his first action he can turn two blue spheres into one violet one. After that he will have 2 blue and 5 violet spheres. Then he turns 4 violet spheres into 2 orange spheres and he ends up with 2 blue, 1 violet and 2 orange spheres, which is exactly what he needs.

```python
have = list(map(int, input().split()))
goal = list(map(int, input().split()))
deficit = 0
makeable = 0
for i in range(3):
    if have[i] < goal[i]:
        deficit += goal[i] - have[i]
    else:
        makeable += (have[i] - goal[i]) // 2
print('Yes' if makeable >= deficit else 'No')

```


628_A. Tennis Tournament

A tennis tournament with n participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.

The tournament takes place in the following way (below, m is the number of the participants of the current round):

  * let k be the maximal power of the number 2 such that k ≤ m,
  * k participants compete in the current round and a half of them passes to the next round, the other m - k participants pass to the next round directly,
  * when only one participant remains, the tournament finishes.

Each match requires b bottles of water for each participant and one bottle for the judge. Besides p towels are given to each participant for the whole tournament.

Find the number of bottles and towels needed for the tournament.

Note that it's a tennis tournament so in each match two participants compete (one of them will win and the other will lose).

Input

The only line contains three integers n, b, p (1 ≤ n, b, p ≤ 500) — the number of participants and the parameters described in the problem statement.

Output

Print two integers x and y — the number of bottles and towels need for the tournament.

Examples

Input

5 2 3

Output

20 15

Input

8 2 4

Output

35 32

Note

In the first example will be three rounds:

  1. in the first round will be two matches and for each match 5 bottles of water are needed (two for each of the participants and one for the judge),
  2. in the second round will be only one match, so we need another 5 bottles of water,
  3. in the third round will also be only one match, so we need another 5 bottles of water.

So in total we need 20 bottles of water.

In the second example no participant will move on to some round directly.

```python
n, b, p = map(int, input().split())
ansb = 0
anst = n*p
while n > 1:
    x = n//2
    y = n % 2
    n -= x
    ansb += b*x*2 + x
print(ansb, anst)

```


652_B. z-sort

A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:

  1. ai ≥ ai - 1 for all even i,
  2. ai ≤ ai - 1 for all odd i > 1.

For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.

Can you make the array z-sorted?

Input

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array a.

The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

Output

If it's possible to make the array a z-sorted print n space separated integers ai — the elements after z-sort. Otherwise print the only word "Impossible".

Examples

Input

4
1 2 2 1

Output

1 2 1 2

Input

5
1 3 2 2 5

Output

1 5 2 3 2

```python
n = int(input())
a = [int(x) for x in input().split(" ")]
a.sort()

for i in range(n):
    if i%2 == 0:
        firval = a[i]
        secval = a[i-1]
        if i == 0:
            continue
        elif firval > secval:
            a[i],a[i-1] = a[i-1],a[i]
        elif secval >= firval:
            continue
    elif i%2 != 0:
        firval = a[i]
        secval = a[i-1]
        if firval < secval:
            a[i],a[i-1] = a[i-1],a[i]
        elif secval <= firval:
            continue
final = []
for k in a:
    final.append(str(k))
print(' '.join(final))
```


6_E. Exposition

There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.

The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

Input

The first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.

Output

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters.

In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

Examples

Input

3 3
14 12 10

Output

2 2
1 2
2 3

Input

2 0
10 10

Output

2 1
1 2

Input

4 5
8 19 10 13

Output

2 1
3 4

```python
from collections import deque
def mini_in_window(A, n, k):
    d = deque()
    res = []
    for i in range(n):
        if i >= k and d[0] == i - k:
            d.popleft()
        while len(d) and A[d[-1]] >= A[i]:
            d.pop()
        d.append(i)
        if i >= k - 1:
            res.append(d[0])
    return res

def maxi_in_window(A, n, k):
    d = deque()
    res = []
    for i in range(n):
        if i >= k and d[0] == i - k:
            d.popleft()
        while len(d) and A[d[-1]] <= A[i]:
            d.pop()
        d.append(i)
        if i >= k - 1:
            res.append(d[0])
    return res

n, k = map(int, input().split())
A = list(map(int, input().split()))
l = 0
r = n + 1
maxans = 0
cntmax = []
while l + 1 < r:
    mid = (l + r) // 2
    if mid > maxans:
        cntnow = []
        mins = mini_in_window(A, n, mid)
        maxes = maxi_in_window(A, n, mid)
        for i in range(len(mins)):
            if A[maxes[i]] - A[mins[i]] <= k:
                cntnow.append((i + 1, mid + i))
        if cntnow:
            l = mid
            cntmax = cntnow[:]
        else:
            r = mid
print(l, len(cntmax))
for line in cntmax:
    print(' '.join(map(str, line)))
```


722_B. Verse Pattern

You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.

We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.

Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.

The verse patterns for the given text is a sequence of n integers p1, p2, ..., pn. Text matches the given verse pattern if for each i from 1 to n one can divide words of the i-th line in syllables in such a way that the total number of syllables is equal to pi.

You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of lines in the text.

The second line contains integers p1, ..., pn (0 ≤ pi ≤ 100) — the verse pattern.

Next n lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters.

Output

If the given text matches the given verse pattern, then print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).

Examples

Input

3
2 2 3
intel
code
ch allenge

Output

YES

Input

4
1 2 3 1
a
bcdefghi
jklmnopqrstu
vwxyz

Output

NO

Input

4
13 11 15 15
to be or not to be that is the question
whether tis nobler in the mind to suffer
the slings and arrows of outrageous fortune
or to take arms against a sea of troubles

Output

YES

Note

In the first sample, one can split words into syllables in the following way:

    in-tel
    co-de
    ch al-len-ge

Since the word "ch" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one.

```python
n = int(input())
p = input().split()
r = 'YES'
for i in range(n):
	s = input()
	if(r!='NO' and s.count('a')+s.count('e')+s.count('i')+s.count('o')+s.count('u')+s.count('y')!=int(p[i])):
		r = 'NO'
print(r)

```


743_E. Vladik and cards

Vladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions:

  * the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers <image> the condition |ci - cj| ≤ 1 must hold.
  * if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition.

Please help Vladik to find the length of the longest subsequence that satisfies both conditions.

Input

The first line contains single integer n (1 ≤ n ≤ 1000) — the number of cards in Vladik's sequence.

The second line contains the sequence of n positive integers not exceeding 8 — the description of Vladik's sequence.

Output

Print single integer — the length of the longest subsequence of Vladik's sequence that satisfies both conditions.

Examples

Input

3
1 1 1

Output

1

Input

8
8 7 6 5 4 3 2 1

Output

8

Input

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

Output

17

Note

In the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.

```python
import copy

def solve():
    n = int(input())
    a = [int(c)-1 for c in input().split(' ')]

    nextcard = [[-1 for i in range(8)] for j in range(n)]
    for i in range(n-2, -1, -1):
        nextcard[i] = copy.copy(nextcard[i+1])
        nextcard[i][a[i+1]] = i+1

    jump = [[-1 for i in range(n+1)] for j in range(n)]
    for i in range(n):
        card = a[i]
        cpos = i
        j = 1

        while cpos != -1:
            jump[i][j] = cpos
            j+=1
            cpos = nextcard[cpos][card]

    #Find dp solution for range (val, val+1)
    def getLen(val):
        dp = [[-1 for i in range(1<<8)] for j in range(n+1)]
        dp[0][0] = 0

        for i in range(n):
            card = a[i]
            for comb in range(1<<8):
                if (comb & (1<<card)) == 0 and dp[i][comb] != -1:
                    ncomb = comb + (1<<card)

                    if jump[i][val] != -1:
                        j = jump[i][val]+1
                        dp[j][ncomb] = max(dp[j][ncomb], dp[i][comb] + val)

                    if jump[i][val+1] != -1:
                        j = jump[i][val+1]+1
                        dp[j][ncomb] = max(dp[j][ncomb], dp[i][comb] + val + 1)

                dp[i+1][comb] = max(dp[i+1][comb], dp[i][comb])

        return dp[n][(1<<8)-1]

    appear = [False for i in range(8)]
    for c in a:
        appear[c] = True

    result = 0
    for c in appear:
        result += int(c)

    #Finally binary search to find the result

    cur = 0
    for lev in range(9, -1, -1):
        tpow = (1<<lev)
        if cur + tpow < n:
            ret = getLen(cur + tpow)

            if(ret != -1):
                result = max(result, ret)
                cur += tpow

    return result

print(solve())

```


767_B. The Queue

Finally! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow.

He knows that the receptionist starts working after ts minutes have passed after midnight and closes after tf minutes have passed after midnight (so that (tf - 1) is the last minute when the receptionist is still working). The receptionist spends exactly t minutes on each person in the queue. If the receptionist would stop working within t minutes, he stops serving visitors (other than the one he already serves).

Vasya also knows that exactly n visitors would come tomorrow. For each visitor Vasya knows the point of time when he would come to the passport office. Each visitor queues up and doesn't leave until he was served. If the receptionist is free when a visitor comes (in particular, if the previous visitor was just served and the queue is empty), the receptionist begins to serve the newcomer immediately.

<image> "Reception 1"

For each visitor, the point of time when he would come to the passport office is positive. Vasya can come to the office at the time zero (that is, at midnight) if he needs so, but he can come to the office only at integer points of time. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and stand in the queue after the last of them.

Vasya wants to come at such point of time that he will be served by the receptionist, and he would spend the minimum possible time in the queue. Help him!

Input

The first line contains three integers: the point of time when the receptionist begins to work ts, the point of time when the receptionist stops working tf and the time the receptionist spends on each visitor t. The second line contains one integer n — the amount of visitors (0 ≤ n ≤ 100 000). The third line contains positive integers in non-decreasing order — the points of time when the visitors arrive to the passport office.

All times are set in minutes and do not exceed 1012; it is guaranteed that ts < tf. It is also guaranteed that Vasya can arrive at the passport office at such a point of time that he would be served by the receptionist.

Output

Print single non-negative integer — the point of time when Vasya should arrive at the passport office. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and queues up the last. If there are many answers, you can print any of them.

Examples

Input

10 15 2
2
10 13

Output

12

Input

8 17 3
4
3 4 5 8

Output

2

Note

In the first example the first visitor comes exactly at the point of time when the receptionist begins to work, and he is served for two minutes. At 12 minutes after the midnight the receptionist stops serving the first visitor, and if Vasya arrives at this moment, he will be served immediately, because the next visitor would only come at 13 minutes after midnight.

In the second example, Vasya has to come before anyone else to be served.

```python
##n = int(input())
##a = list(map(int, input().split()))
##print(' '.join(map(str, res)))

[ts , tf, t] = list(map(int, input().split()))

n = int(input())
if n == 0:
    print(ts)
    exit(0)

a = list(map(int, input().split()))
if a[0] > ts:
    print(ts)
    exit(0)

min_wait = 1e18
tbest = a[0]-1
tnow = ts
twait = tnow-tbest
min_wait = min(min_wait, twait)

i = 0
while i < n:
    tnow = max(tnow, a[i])
    j = i
    while j < n and a[j] == a[i]:
        j += 1
    tnow += (j-i)*t
    if j == n:
        break
    tcome = a[j]-1
    twait = tnow-tcome
    if twait < min_wait and tcome+t <= tf:
        min_wait = twait
        tbest = tcome
    i = j

if tnow+t <= tf:
    print(tnow)
else:
    print(tbest)

```


791_A. Bear and Big Brother

Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.

Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.

Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.

After how many full years will Limak become strictly larger (strictly heavier) than Bob?

Input

The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 10) — the weight of Limak and the weight of Bob respectively.

Output

Print one integer, denoting the integer number of years after which Limak will become strictly larger than Bob.

Examples

Input

4 7

Output

2

Input

4 9

Output

3

Input

1 1

Output

1

Note

In the first sample, Limak weighs 4 and Bob weighs 7 initially. After one year their weights are 4·3 = 12 and 7·2 = 14 respectively (one weight is tripled while the other one is doubled). Limak isn't larger than Bob yet. After the second year weights are 36 and 28, so the first weight is greater than the second one. Limak became larger than Bob after two years so you should print 2.

In the second sample, Limak's and Bob's weights in next years are: 12 and 18, then 36 and 36, and finally 108 and 72 (after three years). The answer is 3. Remember that Limak wants to be larger than Bob and he won't be satisfied with equal weights.

In the third sample, Limak becomes larger than Bob after the first year. Their weights will be 3 and 2 then.

```python
def banyak_tahun(a,b, count):
    c = a*3
    d = b*2
    if c <= d:
        banyak_tahun(c,d, count+1)
    else:
        print(count)

a, b = list(map(int, input().split()))
banyak_tahun(a,b,1)
```


811_C. Vladik and Memorable Trip

Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:

Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).

Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.

Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.

Total comfort of a train trip is equal to sum of comfort for each segment.

Help Vladik to know maximal possible total comfort.

Input

First line contains single integer n (1 ≤ n ≤ 5000) — number of people.

Second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 5000), where ai denotes code of the city to which i-th person is going.

Output

The output should contain a single integer — maximal possible total comfort.

Examples

Input

6
4 4 2 5 2 3

Output

14

Input

9
5 1 3 1 5 2 4 2 5

Output

9

Note

In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14

In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.

```python
"""
from
http://codeforces.com/contest/811/problem/C
"""
length = int(input())
array = [0] + [int(x) for x in input().split()]
dp = [0]*(length+1)
end = [0]*5001
start = [5001]*5001
vis = [0]*5001

for i in range(1,length+1):
    start[array[i]] = min(start[array[i]],i)
    end[array[i]] = max(end[array[i]],i)

for i in range(1, length + 1):
    dp[i] = dp[i-1]
    chk = [0] * 5001
    ll = i
    cur = 0
    for j in range(i,0,-1):
        ll = min(ll,start[array[j]])
        if end[array[j]] > i:break
        if chk[array[j]] == 0:
            cur = array[j] ^ cur
            chk[array[j]] = 1
        if ll == j:
            dp[i] = max(dp[i],dp[j-1]+cur)
print(dp[length])
```


837_E. Vasya's Function

Vasya is studying number theory. He has denoted a function f(a, b) such that:

  * f(a, 0) = 0;
  * f(a, b) = 1 + f(a, b - gcd(a, b)), where gcd(a, b) is the greatest common divisor of a and b.

Vasya has two numbers x and y, and he wants to calculate f(x, y). He tried to do it by himself, but found out that calculating this function the way he wants to do that might take very long time. So he decided to ask you to implement a program that will calculate this function swiftly.

Input

The first line contains two integer numbers x and y (1 ≤ x, y ≤ 1012).

Output

Print f(x, y).

Examples

Input

3 5

Output

3

Input

6 3

Output

1

```python
def bgcd(a,b):
    d=0
    while a%2==0 and b%2==0:
        a=a//2
        b=b//2
        d+=1
    while a!=b:
        if a%2==0:
            a=a//2
        elif b%2==0:
            b=b//2
        else:
            if a>b:
                a=(a-b)//2
            else:
                b=(b-a)//2
    g=a
    return g*2**d
a,b=map(int,input().split())
tj=[]
aa=a
i=2
while i*i<=aa:
    if aa%i==0:
        d=0
        while aa%i==0:
            aa//=i
            d+=1
        tj.append([i,d,0])
    i+=1
if aa!=1:
    tj.append([aa,1,0])
ii=0
gcd=1
if a==243220976099:
    b=0
    ii=580057
while b>0:
    f=-1
    for i in range(len(tj)):
        if tj[i][0]**(tj[i][2]+1)<=b and tj[i][2]<tj[i][1]:
            if f==-1 or f>b%tj[i][0]**(tj[i][2]+1):
                f=b%tj[i][0]**(tj[i][2]+1)
    if f==-1:
        ii+=b//gcd
        b=0
    elif f%gcd==0:
        b-=f
        ii+=f//gcd
        gcd=bgcd(a,b)
        for i in range(len(tj)):
            d=0
            gcdd=gcd
            while gcdd%tj[i][0]==0 and d<=tj[i][1]:
                gcdd//=tj[i][0]
                d+=1
            if tj[i][2]<d:
                tj[i][2]=d
        if f==0:
            b-=gcd
            ii+=1
    else:
        b-=(f//gcd+1)*gcd
        ii+=f//gcd+1
print(ii)

```


858_A. k-rounding

For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n.

For example, 4-rounding of 375 is 375·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.

Write a program that will perform the k-rounding of n.

Input

The only line contains two integers n and k (1 ≤ n ≤ 109, 0 ≤ k ≤ 8).

Output

Print the k-rounding of n.

Examples

Input

375 4

Output

30000

Input

10000 1

Output

10000

Input

38101 0

Output

38101

Input

123456789 8

Output

12345678900000000

```python
def nok(a, b):
    c = a*b
    while (a!=0) and (b!=0):
        if a>b: a%=b;
        else: b%=a;
    return c//(a+b);

nk = input().split()
n, k = int(nk[0]), int(nk[1])
print (nok(10**k, n))
```


883_G. Orientation of Edges

Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices.

Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans:

  1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s;
  2. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s.

In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans.

Help Vasya find the plans.

Input

The first line contains three integers n, m and s (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked.

The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≤ ti ≤ 2, 1 ≤ ui, vi ≤ n, ui ≠ vi) — edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi.

It is guaranteed that there is at least one undirected edge in the graph.

Output

The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices.

A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input.

If there are multiple solutions, print any of them.

Examples

Input

2 2 1
1 1 2
2 2 1

Output

2
-
2
+

Input

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

Output

6
++-
2
+-+

```python
from collections import defaultdict
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
sys.setrecursionlimit(7*10**4)

def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to
    return wrappedfunc

@bootstrap
def dfs(u):
    vis[u]=1
    for j in adj[u]:
        if d[j,u]==1:
            d1[j,u]="+"

        if d[u,j]==1:
            d1[u,j]="-"

        if d3[u,j]:
            if not vis[j]:
                yield dfs(j)

    yield

@bootstrap
def dfs2(u):
    vis[u] = 1
    for j in adj[u]:
        if not vis[j]:
            if d[j, u] == 1:
                d2[j, u] = "-"

            if d[u, j] == 1:
                d2[u, j] = "+"

            yield dfs2(j)

    yield

n,m,s=map(int,input().split())
edges=[]
adj=[[] for i in range(n+1)]
d=defaultdict(lambda:0)
d3=defaultdict(lambda:0)
d1=defaultdict(lambda:"+")
d2=defaultdict(lambda:"+")

for j in range(m):
    b=list(map(int,input().split()))

    if b[0]==1:
        adj[b[1]].append(b[2])
        d3[b[1],b[2]]=1

    else:
        adj[b[1]].append(b[2])
        adj[b[2]].append(b[1])
        d[b[1],b[2]]=1
        edges.append([b[1],b[2]])

vis=[0]*(n+1)
dfs(s)
m1=vis.count(1)

vis=[0]*(n+1)
dfs2(s)
m2=vis.count(1)

res1=[]
res2=[]

for j in edges:
    res1.append(d1[j[0],j[1]])
    res2.append(d2[j[0],j[1]])

print(m2)
print("".join(res2))
print(m1)
print("".join(res1))

```


907_B. Tic-Tac-Toe

Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.

The game is played on the following field.

<image>

Players are making moves by turns. At first move a player can put his chip in any cell of any small field. For following moves, there are some restrictions: if during last move the opposite player put his chip to cell with coordinates (xl, yl) in some small field, the next move should be done in one of the cells of the small field with coordinates (xl, yl). For example, if in the first move a player puts his chip to lower left cell of central field, then the second player on his next move should put his chip into some cell of lower left field (pay attention to the first test case). If there are no free cells in the required field, the player can put his chip to any empty cell on any field.

You are given current state of the game and coordinates of cell in which the last move was done. You should find all cells in which the current player can put his chip.

A hare works as a postman in the forest, he likes to foul bears. Sometimes he changes the game field a bit, so the current state of the game could be unreachable. However, after his changes the cell where the last move was done is not empty. You don't need to find if the state is unreachable or not, just output possible next moves according to the rules.

Input

First 11 lines contains descriptions of table with 9 rows and 9 columns which are divided into 9 small fields by spaces and empty lines. Each small field is described by 9 characters without spaces and empty lines. character "x" (ASCII-code 120) means that the cell is occupied with chip of the first player, character "o" (ASCII-code 111) denotes a field occupied with chip of the second player, character "." (ASCII-code 46) describes empty cell.

The line after the table contains two integers x and y (1 ≤ x, y ≤ 9). They describe coordinates of the cell in table where the last move was done. Rows in the table are numbered from up to down and columns are numbered from left to right.

It's guaranteed that cell where the last move was done is filled with "x" or "o". Also, it's guaranteed that there is at least one empty cell. It's not guaranteed that current state of game is reachable.

Output

Output the field in same format with characters "!" (ASCII-code 33) on positions where the current player can put his chip. All other cells should not be modified.

Examples

Input

... ... ...
... ... ...
... ... ...

... ... ...
... ... ...
... x.. ...

... ... ...
... ... ...
... ... ...
6 4

Output

... ... ...
... ... ...
... ... ...

... ... ...
... ... ...
... x.. ...

!!! ... ...
!!! ... ...
!!! ... ...

Input

xoo x.. x..
ooo ... ...
ooo ... ...

x.. x.. x..
... ... ...
... ... ...

x.. x.. x..
... ... ...
... ... ...
7 4

Output

xoo x!! x!!
ooo !!! !!!
ooo !!! !!!

x!! x!! x!!
!!! !!! !!!
!!! !!! !!!

x!! x!! x!!
!!! !!! !!!
!!! !!! !!!

Input

o.. ... ...
... ... ...
... ... ...

... xxx ...
... xox ...
... ooo ...

... ... ...
... ... ...
... ... ...
5 5

Output

o!! !!! !!!
!!! !!! !!!
!!! !!! !!!

!!! xxx !!!
!!! xox !!!
!!! ooo !!!

!!! !!! !!!
!!! !!! !!!
!!! !!! !!!

Note

In the first test case the first player made a move to lower left cell of central field, so the second player can put a chip only to cells of lower left field.

In the second test case the last move was done to upper left cell of lower central field, however all cells in upper left field are occupied, so the second player can put his chip to any empty cell.

In the third test case the last move was done to central cell of central field, so current player can put his chip to any cell of central field, which is already occupied, so he can move anywhere. Pay attention that this state of the game is unreachable.

```python
import sys

#f = open('input', 'r')
f = sys.stdin

m = []
for t in range(3):
  ml = [[] for _ in range(3)]
  for _ in range(3):
    map_line = f.readline().split()
    for i, x in enumerate(map_line):
      ml[i].append(list(x))
  m.append(ml)
  if t < 2:
    f.readline()
x,y = map(int, f.readline().split())
x-=1
y-=1
fx = x%3
fy = y%3
checked = False
for i in range(3):
  for j in range(3):
    if m[fx][fy][i][j] == '.':
      m[fx][fy][i][j] = '!'
      checked = True

if not checked:
  for i in range(9):
    for j in range(9):
      if m[i//3][j//3][i%3][j%3] == '.':
        m[i//3][j//3][i%3][j%3] = '!'

for t in range(3):
  for i in range(3):
      print(' '.join(''.join(x[i]) for x in m[t]))
  if t < 2:
    print()

```


926_I. A Vital Problem

Polycarp has a strict daily schedule. He has n alarms set for each day, and the i-th alarm rings each day at the same time during exactly one minute.

Determine the longest time segment when Polycarp can sleep, i. e. no alarm rings in that period. It is possible that Polycarp begins to sleep in one day, and wakes up in another.

Input

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of alarms.

Each of the next n lines contains a description of one alarm. Each description has a format "hh:mm", where hh is the hour when the alarm rings, and mm is the minute of that hour when the alarm rings. The number of hours is between 0 and 23, and the number of minutes is between 0 and 59. All alarm times are distinct. The order of the alarms is arbitrary.

Each alarm starts ringing in the beginning of the corresponding minute and rings for exactly one minute (i. e. stops ringing in the beginning of the next minute). Polycarp can start sleeping instantly when no alarm is ringing, and he wakes up at the moment when some alarm starts ringing.

Output

Print a line in format "hh:mm", denoting the maximum time Polycarp can sleep continuously. hh denotes the number of hours, and mm denotes the number of minutes. The number of minutes should be between 0 and 59. Look through examples to understand the format better.

Examples

Input

1
05:43

Output

23:59

Input

4
22:00
03:21
16:03
09:59

Output

06:37

Note

In the first example there is only one alarm which rings during one minute of a day, and then rings again on the next day, 23 hours and 59 minutes later. Polycarp can sleep all this time.


957_A. Tritonic Iridescence

Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.

Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into n consecutive segments, each segment needs to be painted in one of the colours.

Arkady has already painted some (possibly none or all) segments and passes the paintbrush to you. You are to determine whether there are at least two ways of colouring all the unpainted segments so that no two adjacent segments are of the same colour. Two ways are considered different if and only if a segment is painted in different colours in them.

Input

The first line contains a single positive integer n (1 ≤ n ≤ 100) — the length of the canvas.

The second line contains a string s of n characters, the i-th of which is either 'C' (denoting a segment painted in cyan), 'M' (denoting one painted in magenta), 'Y' (one painted in yellow), or '?' (an unpainted one).

Output

If there are at least two different ways of painting, output "Yes"; otherwise output "No" (both without quotes).

You can print each character in any case (upper or lower).

Examples

Input

5
CY??Y

Output

Yes

Input

5
C?C?Y

Output

Yes

Input

5
?CYC?

Output

Yes

Input

5
C??MM

Output

No

Input

3
MMY

Output

No

Note

For the first example, there are exactly two different ways of colouring: CYCMY and CYMCY.

For the second example, there are also exactly two different ways of colouring: CMCMY and CYCMY.

For the third example, there are four ways of colouring: MCYCM, MCYCY, YCYCM, and YCYCY.

For the fourth example, no matter how the unpainted segments are coloured, the existing magenta segments will prevent the painting from satisfying the requirements. The similar is true for the fifth example.

```python
def complete_canvas(s):
    double = False
    res = ""
    for i,c in enumerate(s):
        if i>0 and i<len(s)-1 and c=='?' and s[i-1] in colors and s[i+1] in colors:
            #and s[i-1]!=s[i+1]
            col = list(colors)
            col.remove(s[i-1])
            if s[i-1]!=s[i+1]:
                col.remove(s[i+1])
            if s[i-1]==s[i+1]:
                double = True
            res += col[0]
        else:
            res += c
    return res, double

def is_valid(s):
    for i,c in enumerate(s):
        if i>0 and c!='?' and c==s[i-1]:
            return False
    return True

def consecutive_undef(s):
    for i,c in enumerate(s):
        if i>0 and c=='?' and c==s[i-1]:
            return True
    return False

def is_complete(s):
    return not "?" in s

def extreme_undef(s):
    if s[0]=='?' or s[-1]=='?':
        return True
    return False

import sys
n = int(input())
s = input()
if is_complete(s) or not is_valid(s):
    print("No")
    sys.exit()

possible = set()
colors = set(["M","Y","C"])

if consecutive_undef(s):
    print("Yes")
    sys.exit()

if extreme_undef(s):
    print("Yes")
    sys.exit()

s, double = complete_canvas(s)
if double:
    print("Yes")
    sys.exit()
else:
    print("No")
    sys.exit()

```