128_A. Statues

In this task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 × 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains a statue cannot have anything or anyone — neither any other statues, nor Anna, nor Maria.

Anna is present on the board as a figurant (she stands still and never moves), and Maria has been actively involved in the game. Her goal is — to come to Anna's square. Maria and statues move in turn, Maria moves first. During one move Maria can go to any adjacent on the side or diagonal cell in which there is no statue, or she can stay in the cell where she is. The statues during their move must go one square down simultaneously, and those statues that were in the bottom row fall from the board and are no longer appeared.

At that moment, when one of the statues is in the cell in which the Maria is, the statues are declared winners. At the moment when Maria comes into the cell where Anna has been waiting, Maria is declared the winner.

Obviously, nothing depends on the statues, so it all depends on Maria. Determine who will win, if Maria does not make a strategic error.

Input

You are given the 8 strings whose length equals 8, describing the initial position on the board. The first line represents the top row of the board, the next one — for the second from the top, and so on, the last line represents the bottom row. Each character string matches a single cell board in the appropriate row, and the characters are in the same manner as that of the corresponding cell. If the cell is empty, the corresponding character is ".". If a cell has Maria, then it is represented by character "M". If a cell has Anna, it is represented by the character "A". If a cell has a statue, then the cell is represented by character "S".

It is guaranteed that the last character of the first row is always "A", the first character of the last line is always "M". The remaining characters are "." or "S".

Output

If Maria wins, print string "WIN". If the statues win, print string "LOSE".

Examples

Input

.......A
........
........
........
........
........
........
M.......

Output

WIN

Input

.......A
........
........
........
........
........
SS......
M.......

Output

LOSE

Input

.......A
........
........
........
........
.S......
S.......
MS......

Output

LOSE

```python
f = []
for i in range(8):
    f.append(input())

d = [[[0 for i in range(8)] for j in range(8)] for k in range(100)]

d[0][7][0] = 1
dx = [1, 1, 1, 0, 0, -1, -1, -1, 0]
dy = [1, 0, -1, 1, -1, 1, 0, -1, 0]

ans = 'LOSE'
for i in range(99):
    for x in range(8):
        for y in range(8):
            if not d[i][x][y]:
                continue
            for j in range(9):
                nx = x + dx[j]
                ny = y + dy[j]
                if not(0 <= nx < 8 and 0 <= ny < 8):
                    continue

                valid = True
                if 0 <= nx - i < 8 and f[nx - i][ny] == 'S':
                    valid = False
                if 0 <= nx - i - 1 < 8 and f[nx - i - 1][ny] == 'S':
                    valid = False

                if not valid:
                    continue
                d[i + 1][nx][ny] = 1
                if nx == 0 and ny == 7:
                    ans = 'WIN'
print(ans)

```


1332_B. Composite Coloring

A positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97.

Alice is given a sequence of n composite numbers a_1,a_2,…,a_n.

She wants to choose an integer m ≤ 11 and color each element one of m colors from 1 to m so that:

  * for each color from 1 to m there is at least one element of this color;
  * each element is colored and colored exactly one color;
  * the greatest common divisor of any two elements that are colored the same color is greater than 1, i.e. \gcd(a_i, a_j)>1 for each pair i, j if these elements are colored the same color.

Note that equal elements can be colored different colors — you just have to choose one of m colors for each of the indices from 1 to n.

Alice showed already that if all a_i ≤ 1000 then she can always solve the task by choosing some m ≤ 11.

Help Alice to find the required coloring. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some m from 1 to 11.

Input

The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Then the descriptions of the test cases follow.

The first line of the test case contains a single integer n (1 ≤ n ≤ 1000) — the amount of numbers in a sequence a.

The second line of the test case contains n composite integers a_1,a_2,…,a_n (4 ≤ a_i ≤ 1000).

It is guaranteed that the sum of n over all test cases doesn't exceed 10^4.

Output

For each test case print 2 lines. The first line should contain a single integer m (1 ≤ m ≤ 11) — the number of used colors. Consider colors to be numbered from 1 to m. The second line should contain any coloring that satisfies the above conditions. Print n integers c_1, c_2, ..., c_n (1 ≤ c_i ≤ m), where c_i is the color of the i-th element. If there are multiple solutions then you can print any of them. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some m from 1 to 11.

Remember that each color from 1 to m should be used at least once. Any two elements of the same color should not be coprime (i.e. their GCD should be greater than 1).

Example

Input

3
3
6 10 15
2
4 9
23
437 519 865 808 909 391 194 291 237 395 323 365 511 497 781 737 871 559 731 697 779 841 961

Output

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

Note

In the first test case, \gcd(6,10)=2, \gcd(6,15)=3 and \gcd(10,15)=5. Therefore, it's valid to color all elements the same color. Note that there are other colorings which satisfy Alice's requirement in this test case.

In the second test case there is only one element of each color, so the coloring definitely satisfies Alice's requirement.

```python
for _ in range(int(input())):
    n=int(input())
    arr=list(map(int,input().split()))

    dct={}
    m=1
    arr1=[]
    for n1 in arr:
        check=-1
        n2=int(n1**(0.5))
        for j in range(2,n2+1,1):
            if(n1%j==0):
                check=0
                if(j in dct.keys()):
                    arr1.append(dct[j])
                else:
                    dct[j]=m
                    arr1.append(m)
                    m+=1
                break
        if(check==-1):
            dct[n1]=m
            arr1.append(m)
            m+=1
    print(m-1)
    for i in arr1:
        print(i,end=" ")
    print()

```


1352_E. Special Elements

Pay attention to the non-standard memory limit in this problem.

In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.

The array a=[a_1, a_2, …, a_n] (1 ≤ a_i ≤ n) is given. Its element a_i is called special if there exists a pair of indices l and r (1 ≤ l < r ≤ n) such that a_i = a_l + a_{l+1} + … + a_r. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).

Print the number of special elements of the given array a.

For example, if n=9 and a=[3,1,4,1,5,9,2,6,5], then the answer is 5:

  * a_3=4 is a special element, since a_3=4=a_1+a_2=3+1;
  * a_5=5 is a special element, since a_5=5=a_2+a_3=1+4;
  * a_6=9 is a special element, since a_6=9=a_1+a_2+a_3+a_4=3+1+4+1;
  * a_8=6 is a special element, since a_8=6=a_2+a_3+a_4=1+4+1;
  * a_9=5 is a special element, since a_9=5=a_2+a_3=1+4.

Please note that some of the elements of the array a may be equal — if several elements are equal and special, then all of them should be counted in the answer.

Input

The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.

Each test case is given in two lines. The first line contains an integer n (1 ≤ n ≤ 8000) — the length of the array a. The second line contains integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n).

It is guaranteed that the sum of the values of n for all test cases in the input does not exceed 8000.

Output

Print t numbers — the number of special elements for each of the given arrays.

Example

Input

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

Output

5
1
0
4
0

```python
import sys
from math import ceil
read=sys.stdin.buffer.readline

mi=lambda:map(int,read().split())
li=lambda:list(mi())
cin=lambda:int(read())
for _ in range(cin()):
    n=cin()
    a=li()
    freq=[0]*(n+1)
    for el in a:
        freq[el]+=1
    ans=0
    for i in range(n-1):
        sm=a[i]
        for j in range(i+1,n):
            sm+=a[j]
            if sm<=n and freq[sm]>0:
                ans+=freq[sm]
                freq[sm]=0
    print(ans)
```


1372_C. Omkar and Baseball

Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across n sessions follow the identity permutation (ie. in the first game he scores 1 point, in the second game he scores 2 points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up!

Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on [1,2,3] can yield [3,1,2] but it cannot yield [3,2,1] since the 2 is in the same position.

Given a permutation of n integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed 10^{18}.

An array a is a subarray of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Input

Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100). Description of the test cases follows.

The first line of each test case contains integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the given permutation.

The second line of each test case contains n integers a_{1},a_{2},...,a_{n} (1 ≤ a_{i} ≤ n) — the initial permutation.

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

Output

For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.

Example

Input

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

Output

0
2

Note

In the first permutation, it is already sorted so no exchanges are needed.

It can be shown that you need at least 2 exchanges to sort the second permutation.

[3, 2, 4, 5, 1, 6, 7]

Perform special exchange on range (1, 5)

[4, 1, 2, 3, 5, 6, 7]

Perform special exchange on range (1, 4)

[1, 2, 3, 4, 5, 6, 7]

```python
import sys
import math
import heapq
import collections
def inputnum():
    return(int(input()))
def inputnums():
    return(map(int,input().split()))
def inputlist():
    return(list(map(int,input().split())))
def inputstring():
    return([x for x in input()])
def inputmatrixchar(rows):
    arr2d = [[j for j in input().strip()] for i in range(rows)]
    return arr2d
def inputmatrixint(rows):
    arr2d = []
    for _ in range(rows):
        arr2d.append([int(i) for i in input().split()])
    return arr2d

t=int(input())
for q in range(t):
    n = inputnum()
    a = inputlist()
    wrong = 0
    firstwrong = False
    secondwrong = False
    for i in range(n):
        if i+1 != a[i]:
            if not firstwrong:
                firstwrong = True
            elif firstwrong and a[i-1] == i and i > 1:
                secondwrong = True
            wrong += 1

    if wrong == 0:
        print(0)
    elif not secondwrong:
        print(1)
    else:
        print(2)
```


1395_B. Boboniu Plays Chess

Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.

You are a new applicant for his company. Boboniu will test you with the following chess question:

Consider a n× m grid (rows are numbered from 1 to n, and columns are numbered from 1 to m). You have a chess piece, and it stands at some cell (S_x,S_y) which is not on the border (i.e. 2 ≤ S_x ≤ n-1 and 2 ≤ S_y ≤ m-1).

From the cell (x,y), you can move your chess piece to (x,y') (1≤ y'≤ m, y' ≠ y) or (x',y) (1≤ x'≤ n, x'≠ x). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.

Your goal is to visit each cell exactly once. Can you find a solution?

Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.

Input

The only line of the input contains four integers n, m, S_x and S_y (3≤ n,m≤ 100, 2 ≤ S_x ≤ n-1, 2 ≤ S_y ≤ m-1) — the number of rows, the number of columns, and the initial position of your chess piece, respectively.

Output

You should print n⋅ m lines.

The i-th line should contain two integers x_i and y_i (1 ≤ x_i ≤ n, 1 ≤ y_i ≤ m), denoting the i-th cell that you visited. You should print exactly nm pairs (x_i, y_i), they should cover all possible pairs (x_i, y_i), such that 1 ≤ x_i ≤ n, 1 ≤ y_i ≤ m.

We can show that under these constraints there always exists a solution. If there are multiple answers, print any.

Examples

Input

3 3 2 2

Output

2 2
1 2
1 3
2 3
3 3
3 2
3 1
2 1
1 1

Input

3 4 2 2

Output

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

Note

Possible routes for two examples:

<image>

```python
def print_column(x1,y1):
    global last
    print(x1,y1)
    a=y1-1
    k=0
    while (a>0):
        print(x1,a)
        a-=1
        k=a+1
    a=y1+1
    while (a<=m):
        print(x1,a)
        a+=1
        k=a-1
    last=k
    #print(f"last spoted at ({x1},{last})")
    return last
def print_marixup(x,y):
    if 1<=x<=n:
        j=print_column(x,y)
        print_marixup(x-1,j)
def print_matrixdwn(x,y):
    if 1<=x<=n:
        j=print_column(x,y)
        print_matrixdwn(x+1,j)
n,m,x,y=map(int,input().split())
sums=0
last=x
print_marixup(x,y)
print_matrixdwn(x+1,last)
```


1419_D2. Sage's Birthday (hard version)

This is the hard version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.

Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row and they are numbered from 1 to n from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.

An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.

You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.

Input

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of ice spheres in the shop.

The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the prices of ice spheres.

Output

In the first line print the maximum number of ice spheres that Sage can buy.

In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.

Example

Input

7
1 3 2 2 4 5 4

Output

3
3 1 4 2 4 2 5

Note

In the sample it's not possible to place the ice spheres in any order so that Sage would buy 4 of them. If the spheres are placed in the order (3, 1, 4, 2, 4, 2, 5), then Sage will buy one sphere for 1 and two spheres for 2 each.

```python
# import os
# import sys
# from io import BytesIO, IOBase

# 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")
import math
# t = int(input())

# for _ in range(t):
n=int(input())
li = [int(i) for i in input().split()]
li.sort()
if n<=2:
    print(0)
    print(*li)
    exit(0)

if n&1:
    p1 = li[:n>>1]
    p2 = li[n>>1:]
    aq = []
    # if p1[-1] == p2[0]:
    #     common = p1[-1]
    #     ctr1 = 0
    #     ctr2 = 0
    #     for i in p1:
    #         if i == common:
    #             ctr1+=1
    #     for i in p2:
    #         if i == common:
    #             ctr2+=1
    #     tctr2 = ctr2
    #     if ctr2 == len(p2):

    #     ans = min(max(len(p2)-ctr2-1,0),ctr1)+min(ctr2,len(p1)-ctr1)
    #     print(ans)
    #     # print(max(ans,0))
    # else:
    #     print(n>>1)
    for i in range(n):
        if i&1:
            aq.append(p1.pop())
            # print(p1.pop(),end=' ')
        else:
            aq.append(p2.pop())
            # print(p2.pop(),end=' ')
    ac = 0
    for p,i in enumerate(aq):
        if p!= 0 and p != n-1 and i < aq[p-1] and i < aq[p+1]:
            ac+=1
    print(ac)
    print(*aq)
else:
    p1 = li[:n>>1]
    p2 = li[n>>1:]
    # if p1[-1] == p2[0]:

    ext = p1.pop()
    aq = []
    # n -= 1
    # if p1[-1] == p2[0]:
    #     common = p1[-1]
    #     ctr1 = 0
    #     ctr2 = 0
    #     for i in p1:
    #         if i == common:
    #             ctr1+=1
    #     for i in p2:
    #         if i == common:
    #             ctr2+=1
    #     mid = min(max(len(p2)-ctr2-1,0),ctr1)
    #     bck = ctr1+ctr2-mid
    #     ans = min(ctr2,len(p1)-ctr1)
    #     print(ans)
    # else:
    #     print(n>>1)
    for i in range(n-1):
        if i&1:
            aq.append(p1.pop())
            # print(p1.pop(),end=' ')
        else:
            aq.append(p2.pop())
            # print(p2.pop(),end=' ')
    aq.append(ext)
    ac = 0
    for p,i in enumerate(aq):
        if p!= 0 and p != n-1 and i < aq[p-1] and i < aq[p+1]:
            ac+=1
    print(ac)
    print(*aq)
    # print(ext)
```


1437_E. Make It Increasing

You are given an array of n integers a_1, a_2, ..., a_n, and a set b of k distinct integers from 1 to n.

In one operation, you may choose two integers i and x (1 ≤ i ≤ n, x can be any integer) and assign a_i := x. This operation can be done only if i does not belong to the set b.

Calculate the minimum number of operations you should perform so the array a is increasing (that is, a_1 < a_2 < a_3 < ... < a_n), or report that it is impossible.

Input

The first line contains two integers n and k (1 ≤ n ≤ 5 ⋅ 10^5, 0 ≤ k ≤ n) — the size of the array a and the set b, respectively.

The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).

Then, if k ≠ 0, the third line follows, containing k integers b_1, b_2, ..., b_k (1 ≤ b_1 < b_2 < ... < b_k ≤ n). If k = 0, this line is skipped.

Output

If it is impossible to make the array a increasing using the given operations, print -1.

Otherwise, print one integer — the minimum number of operations you have to perform.

Examples

Input

7 2
1 2 1 1 3 5 1
3 5

Output

4

Input

3 3
1 3 2
1 2 3

Output

-1

Input

5 0
4 3 1 2 3

Output

2

Input

10 3
1 3 5 6 12 9 8 10 13 15
2 4 9

Output

3

```python
import bisect
def stablesort(s,l6):
    l3 = []
    l4 = [0]
    for i in range(len(s)):
        if l6[0] == -1:
            if s[i]<=l[l6[1]]:
                k = bisect.bisect(l3,s[i])
                if len(l3) == 0 or l3[-1]<=s[i]:
                    l3.append(s[i])
                    l4.append(l4[-1] + 1)
                else:
                    l3[k] = s[i]
        else:
            if l[l6[1]]>=s[i]>=l[l6[0]]:
                k = bisect.bisect(l3,s[i])
                if len(l3) == 0 or l3[-1]<=s[i]:
                    l3.append(s[i])
                    l4.append(l4[-1] + 1)
                else:
                    l3[k] = s[i]
    return(len(l3))
n,k = map(int,input().split())
l = list(map(int,input().split())) + [float('inf')]
l2 = []
tt = 0
for i in range(n):
    l[i] -=i
if k>0:
    kk = list(map(int,input().split()))
if k>0:
    for i in range(k-1):
        if l[kk[i] - 1]>l[kk[i+1] - 1]:
            tt = 1
            break
    if tt == 1:
        print(-1)
        exit(0)
    else:
        ans = 0
        w = 0
        c = 0
        l5 = []
        for i in range(0,k):
            l1 = []
            for j in range(c,kk[i]-1):
                l1.append(l[j])
            if len(l1)>0:
                l2.append(l1)
                l5.append([c-1,kk[i] - 1])
            w = l[kk[i] - 1]
            c = kk[i]
        l1 = []
        for i in range(c,n):
            l1.append(l[i])
        if len(l1)>0:
            l2.append(l1)
            l5.append([c-1,n])
else:
    l3 = []
    for i in range(n):
        k = bisect.bisect(l3,l[i])
        if len(l3) == 0 or l3[-1]<=l[i]:
            l3.append(l[i])
        else:
            l3[k] = l[i]
    print(n-len(l3))
    exit(0)
if len(l2)>0:
    for i in range(len(l2)):
        c = stablesort(l2[i],l5[i])
        ans+=c
    print(n-(ans+k))
else:
    print(n-k)

```


1462_C. Unique Number

You are given a positive number x. Find the smallest positive integer number that has the sum of digits equal to x and all digits are distinct (unique).

Input

The first line contains a single positive integer t (1 ≤ t ≤ 50) — the number of test cases in the test. Then t test cases follow.

Each test case consists of a single integer number x (1 ≤ x ≤ 50).

Output

Output t answers to the test cases:

  * if a positive integer number with the sum of digits equal to x and all digits are different exists, print the smallest such number;
  * otherwise print -1.

Example

Input

4
1
5
15
50

Output

1
5
69
-1

```python
test=int(input())
for testcase in range(test):
    n=int(input())
    if(n<=45):
        if(n<10):
            print(n)
        else:
            i=9
            s=0
            ans=0
            while(i>0):
                #print(i)
                if(s+i<=n):
                    s+=i
                    ans=(ans*10)+i

                if(s>=n):
                    break
                i-=1

            if(n==s):
                ans=str(ans)
                print(ans[::-1])
            else:
                print(-1)
    else:
        print(-1)
```


1487_D. Pythagorean Triples

A Pythagorean triple is a triple of integer numbers (a, b, c) such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to a, b and c, respectively. An example of the Pythagorean triple is (3, 4, 5).

Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: c = a^2 - b.

Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple (3, 4, 5): 5 = 3^2 - 4, so, according to Vasya's formula, it is a Pythagorean triple.

When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers (a, b, c) with 1 ≤ a ≤ b ≤ c ≤ n such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.

Input

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

Each test case consists of one line containing one integer n (1 ≤ n ≤ 10^9).

Output

For each test case, print one integer — the number of triples of integers (a, b, c) with 1 ≤ a ≤ b ≤ c ≤ n such that they are Pythagorean according both to the real definition and to the formula Vasya came up with.

Example

Input

3
3
6
9

Output

0
1
1

Note

The only Pythagorean triple satisfying c = a^2 - b with 1 ≤ a ≤ b ≤ c ≤ 9 is (3, 4, 5); that's why the answer for n = 3 is 0, and the answer for n = 6 (and for n = 9) is 1.

```python
import math

t = int(input())
for _ in range(t):
    n = int(input())
    n = math.floor(math.sqrt(n+n-1))
    if n%2==0:
        print((n//2)-1)
    else:
        print(((n+1)//2)-1)
```


1511_A. Review Site

You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote.

However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes.

n reviewers enter the site one by one. Each reviewer is one of the following types:

  * type 1: a reviewer has watched the movie, and they like it — they press the upvote button;
  * type 2: a reviewer has watched the movie, and they dislike it — they press the downvote button;
  * type 3: a reviewer hasn't watched the movie — they look at the current number of upvotes and downvotes of the movie on the server they are in and decide what button to press. If there are more downvotes than upvotes, then a reviewer downvotes the movie. Otherwise, they upvote the movie.

Each reviewer votes on the movie exactly once.

Since you have two servers, you can actually manipulate the votes so that your movie gets as many upvotes as possible. When a reviewer enters a site, you know their type, and you can send them either to the first server or to the second one.

What is the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to?

Input

The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of testcases.

Then the descriptions of t testcases follow.

The first line of each testcase contains a single integer n (1 ≤ n ≤ 50) — the number of reviewers.

The second line of each testcase contains n integers r_1, r_2, ..., r_n (1 ≤ r_i ≤ 3) — the types of the reviewers in the same order they enter the site.

Output

For each testcase print a single integer — the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to.

Example

Input

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

Output

0
2
5
2

Note

In the first testcase of the example you can send the only reviewer to either of the servers — they'll downvote anyway. The movie won't receive any upvotes.

In the second testcase of the example you can send all reviewers to the first server:

  * the first reviewer upvotes;
  * the second reviewer downvotes;
  * the last reviewer sees that the number of downvotes is not greater than the number of upvotes — upvote themselves.

There are two upvotes in total. Alternatevely, you can send the first and the second reviewers to the first server and the last reviewer — to the second server:

  * the first reviewer upvotes on the first server;
  * the second reviewer downvotes on the first server;
  * the last reviewer sees no upvotes or downvotes on the second server — upvote themselves.

```python
t = int(input())
for _ in range(t):
    n = int(input())
    ans = 0
    a = [int(i) for i in input().split()]
    for i in a:
        if i == 1 or i == 3:
            ans += 1
    print(ans)
```


1538_F. Interesting Function

You are given two integers l and r, where l < r. We will add 1 to l until the result is equal to r. Thus, there will be exactly r-l additions performed. For each such addition, let's look at the number of digits that will be changed after it.

For example:

  * if l=909, then adding one will result in 910 and 2 digits will be changed;
  * if you add one to l=9, the result will be 10 and 2 digits will also be changed;
  * if you add one to l=489999, the result will be 490000 and 5 digits will be changed.

Changed digits always form a suffix of the result written in the decimal system.

Output the total number of changed digits, if you want to get r from l, adding 1 each time.

Input

The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.

Each test case is characterized by two integers l and r (1 ≤ l < r ≤ 10^9).

Output

For each test case, calculate the total number of changed digits if you want to get r from l, adding one each time.

Example

Input

4
1 9
9 10
10 20
1 1000000000

Output

8
2
11
1111111110

```python
def count(s):
    ans = 0
    for i in range(len(s), 0 ,-1):
        ans += int(s[:i])
    return ans

for t in range(int(input())):

    l, r = input().split()
    print(count(r) - count(l))

```


165_A. Supercentral Point

One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y):

  * point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y
  * point (x', y') is (x, y)'s left neighbor, if x' < x and y' = y
  * point (x', y') is (x, y)'s lower neighbor, if x' = x and y' < y
  * point (x', y') is (x, y)'s upper neighbor, if x' = x and y' > y

We'll consider point (x, y) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.

Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.

Input

The first input line contains the only integer n (1 ≤ n ≤ 200) — the number of points in the given set. Next n lines contain the coordinates of the points written as "x y" (without the quotes) (|x|, |y| ≤ 1000), all coordinates are integers. The numbers in the line are separated by exactly one space. It is guaranteed that all points are different.

Output

Print the only number — the number of supercentral points of the given set.

Examples

Input

8
1 1
4 2
3 1
1 2
0 2
0 1
1 0
1 3

Output

2

Input

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

Output

1

Note

In the first sample the supercentral points are only points (1, 1) and (1, 2).

In the second sample there is one supercental point — point (0, 0).


186_B. Growing Mushrooms

Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.

Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.

After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.

Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.

Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.

The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).

Input

The first input line contains four integer numbers n, t1, t2, k (1 ≤ n, t1, t2 ≤ 1000; 1 ≤ k ≤ 100) — the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.

Each of the following n lines contains two integers. The i-th (1 ≤ i ≤ n) line contains space-separated integers ai, bi (1 ≤ ai, bi ≤ 1000) — the speeds which the participant number i chose.

Output

Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.

Examples

Input

2 3 3 50
2 4
4 2

Output

1 15.00
2 15.00

Input

4 1 1 1
544 397
280 101
280 101
693 970

Output

4 1656.07
1 937.03
2 379.99
3 379.99

Note

  * First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2·3·0.5 + 4·3 > 4·3·0.5 + 2·3.

```python
n, t1, t2, k = map(int, input().split())
a = n * [0]
list_indexes = []
for i in range(n):
    x = list(map(int, input().split()))
    x.sort()
    a[i] = x
for j in range(n):
    a[j] = max((a[j][0] * t1 * ((100 - k) / 100) + a[j][1] * t2),
               (a[j][1] * t1 * ((100 - k) / 100) + a[j][0] * t2))
    list_indexes.append(j + 1)
v = a.copy()
a.sort(reverse=True)
for _ in range(n):
    if v.count(a[_]) == 1:
        print(v.index(a[_]) + 1, '%.2f' % a[_])
    else:
        print(v.index(a[_]) + 1, '%.2f' % a[_])
        v[v.index(a[_])] = 0

```


207_D4. The Beaver's Problem - 3

The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem:

You've got some training set of documents. For each document you know its subject. The subject in this problem is an integer from 1 to 3. Each of these numbers has a physical meaning. For instance, all documents with subject 3 are about trade.

You can download the training set of documents at the following link: http://download4.abbyy.com/a2/X2RZ2ZWXBG5VYWAL61H76ZQM/train.zip. The archive contains three directories with names "1", "2", "3". Directory named "1" contains documents on the 1-st subject, directory "2" contains documents on the 2-nd subject, and directory "3" contains documents on the 3-rd subject. Each document corresponds to exactly one file from some directory.

All documents have the following format: the first line contains the document identifier, the second line contains the name of the document, all subsequent lines contain the text of the document. The document identifier is used to make installing the problem more convenient and has no useful information for the participants.

You need to write a program that should indicate the subject for a given document. It is guaranteed that all documents given as input to your program correspond to one of the three subjects of the training set.

Input

The first line contains integer id (0 ≤ id ≤ 106) — the document identifier. The second line contains the name of the document. The third and the subsequent lines contain the text of the document. It is guaranteed that the size of any given document will not exceed 10 kilobytes.

The tests for this problem are divided into 10 groups. Documents of groups 1 and 2 are taken from the training set, but their identifiers will not match the identifiers specified in the training set. Groups from the 3-rd to the 10-th are roughly sorted by the author in ascending order of difficulty (these groups contain documents which aren't present in the training set).

Output

Print an integer from 1 to 3, inclusive — the number of the subject the given document corresponds to.

Examples


281_B. Nearest Fraction

You are given three positive integers x, y, n. Your task is to find the nearest fraction to fraction <image> whose denominator is no more than n.

Formally, you should find such pair of integers a, b (1 ≤ b ≤ n; 0 ≤ a) that the value <image> is as minimal as possible.

If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator.

Input

A single line contains three integers x, y, n (1 ≤ x, y, n ≤ 105).

Output

Print the required fraction in the format "a/b" (without quotes).

Examples

Input

3 7 6

Output

2/5

Input

7 2 4

Output

7/2

```python
import sys
from fractions import Fraction

def input():    return sys.stdin.readline().strip()
def iinput():   return int(input())
def rinput():   return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1e9)+7

x, y, n = rinput()
ans = Fraction(x, y).limit_denominator(n)
print(str(ans.numerator)+'/'+str(ans.denominator))
```


304_A. Pythagorean Theorem II

In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states:

In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle).

The theorem can be written as an equation relating the lengths of the sides a, b and c, often called the Pythagorean equation:

a2 + b2 = c2

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides.

<image>

Given n, your task is to count how many right-angled triangles with side-lengths a, b and c that satisfied an inequality 1 ≤ a ≤ b ≤ c ≤ n.

Input

The only line contains one integer n (1 ≤ n ≤ 104) as we mentioned above.

Output

Print a single integer — the answer to the problem.

Examples

Input

5

Output

1

Input

74

Output

35

```python
def gcd(a, b):
    c = a % b
    return gcd(b, c) if c else b
from math import sqrt
n = int(input())
print(sum(n // (x * x + y * y) for x in range(1, int(sqrt(n // 2)) + 1) for y in range(x + 1, int(sqrt(n - x * x)) + 1, 2) if gcd(x, y) == 1))
```


330_B. Road Construction

A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given m pairs of cities — roads cannot be constructed between these pairs of cities.

Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.

Input

The first line consists of two integers n and m <image>.

Then m lines follow, each consisting of two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that it is not possible to construct a road connecting cities ai and bi. Consider the cities are numbered from 1 to n.

It is guaranteed that every pair of cities will appear at most once in the input.

Output

You should print an integer s: the minimum number of roads that should be constructed, in the first line. Then s lines should follow, each consisting of two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that a road should be constructed between cities ai and bi.

If there are several solutions, you may print any of them.

Examples

Input

4 1
1 3

Output

3
1 2
4 2
2 3

Note

This is one possible solution of the example:

<image>

These are examples of wrong solutions:

<image> The above solution is wrong because it doesn't use the minimum number of edges (4 vs 3). In addition, it also tries to construct a road between cities 1 and 3, while the input specifies that it is not allowed to construct a road between the pair. <image> The above solution is wrong because you need to traverse at least 3 roads to go from city 1 to city 3, whereas in your country it must be possible to go from any city to another by traversing at most 2 roads. <image> Finally, the above solution is wrong because it must be possible to go from any city to another, whereas it is not possible in this country to go from city 1 to 3, 2 to 3, and 4 to 3.

```python
__author__ = 'Rajan'

n,m = map(int,input().split())
# n nodes and m edges
hash = [False for i in range(n+1)]
for i in range(m):
    a,b = map(int,input().split())
    hash[a] = hash[b] = True
b = 0
for i in range(1,n+1):
    if not hash[i]:
        b = i
        break

print(n-1)
for i in range(1,n+1):
    if i != b:
        print(i,b)
```


351_E. Jeff and Permutation

Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday.

Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 ≤ i < j ≤ n), such that an inequality ai > aj holds.

Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.

Input

The first line contains integer n (1 ≤ n ≤ 2000). The next line contains n integers — sequence p1, p2, ..., pn (|pi| ≤ 105). The numbers are separated by spaces.

Output

In a single line print the answer to the problem — the minimum number of inversions Jeff can get.

Examples

Input

2
2 1

Output

0

Input

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

Output

6

```python
n = int(input())
inp = input()
seq = inp.split(' ')
seq = [ abs(int(x)) for x in seq ]
Max = max(seq)
nxt = [0] * n
cnt = [0] * n
pos = [n] * (Max+1)
for i in range(n-1, -1, -1):
    nxt[i] = pos[seq[i]]
    pos[seq[i]] = i
for i in range(0, Max+1):
    j = pos[i]
    while(j<n):
        front = sum(cnt[0:j])
        back  = sum(cnt[j+1:n])
        if(front < back):
            seq[j] = 0 - seq[j]
        j = nxt[j]
    j = pos[i]
    while(j < n):
        cnt[j] = 1
        j = nxt[j]
#for i in range(0, n-1):
#    print(seq[i], sep=' ')
#print(seq[n-1])
inv = 0
for i in range(len(seq)):
    for j in range(i+1, len(seq)):
        if(seq[i] > seq[j]):
            inv += 1
print(inv)

```


376_A. Lever

You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.

The decoding of the lever description is given below.

  * If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
  * If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
  * If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.

Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.

Input

The first line contains the lever description as a non-empty string s (3 ≤ |s| ≤ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.

To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.

Output

Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.

Examples

Input

=^==

Output

balance

Input

9===^==1

Output

left

Input

2==^7==

Output

right

Input

41^52==

Output

balance

Note

As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.

The pictures to the examples:

<image> <image> <image> <image>

```python
a=input()
x=a.index('^')
c=0
for i in range(len(a)):
    if a[i]in['^','=']:continue
    c+=int(a[i])*(i-x)
print("right"if c>0else("left"if c<0else"balance"))

```


420_D. Cup Trick

The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.

The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.

But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:

  * each cup contains a mark — a number from 1 to n; all marks on the cups are distinct;
  * the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).

When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.

Input

The first line contains integers n and m (1 ≤ n, m ≤ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≤ xi, yi ≤ n) — the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.

Output

If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.

If there are multiple correct answers, you should print the lexicographically minimum one.

Examples

Input

2 1
2 1

Output

2 1

Input

3 2
1 2
1 1

Output

2 1 3

Input

3 3
1 3
2 3
1 3

Output

-1

```python
import io
import os

# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py

class UnsortedList:
    def __init__(self, iterable=[], _load=200):
        """Initialize sorted list instance."""
        values = sorted(iterable)
        self._len = _len = len(values)
        self._load = _load
        self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
        self._list_lens = [len(_list) for _list in _lists]
        # self._mins = [_list[0] for _list in _lists]
        self._fen_tree = []
        self._rebuild = True

    def _fen_build(self):
        """Build a fenwick tree instance."""
        self._fen_tree[:] = self._list_lens
        _fen_tree = self._fen_tree
        for i in range(len(_fen_tree)):
            if i | i + 1 < len(_fen_tree):
                _fen_tree[i | i + 1] += _fen_tree[i]
        self._rebuild = False

    def _fen_update(self, index, value):
        """Update `fen_tree[index] += value`."""
        if not self._rebuild:
            _fen_tree = self._fen_tree
            while index < len(_fen_tree):
                _fen_tree[index] += value
                index |= index + 1

    def _fen_query(self, end):
        """Return `sum(_fen_tree[:end])`."""
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        x = 0
        while end:
            x += _fen_tree[end - 1]
            end &= end - 1
        return x

    def _fen_findkth(self, k):
        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
        _list_lens = self._list_lens
        if k < _list_lens[0]:
            return 0, k
        if k >= self._len - _list_lens[-1]:
            return len(_list_lens) - 1, k + _list_lens[-1] - self._len
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        idx = -1
        for d in reversed(range(len(_fen_tree).bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
                idx = right_idx
                k -= _fen_tree[idx]
        return idx + 1, k

    def _delete(self, pos, idx):
        """Delete value at the given `(pos, idx)`."""
        _lists = self._lists
        # _mins = self._mins
        _list_lens = self._list_lens

        self._len -= 1
        self._fen_update(pos, -1)
        del _lists[pos][idx]
        _list_lens[pos] -= 1

        if _list_lens[pos]:
            # _mins[pos] = _lists[pos][0]
            pass
        else:
            del _lists[pos]
            del _list_lens[pos]
            # del _mins[pos]
            self._rebuild = True

    def __len__(self):
        """Return the size of the sorted list."""
        return self._len

    def __getitem__(self, index):
        """Lookup value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        return self._lists[pos][idx]

    def __delitem__(self, index):
        """Remove value at `index` from sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._delete(pos, idx)

    def __setitem__(self, index, value):
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._lists[pos][idx] = value

    def insert(self, index, value):
        _load = self._load
        _lists = self._lists
        _list_lens = self._list_lens

        if _lists:
            pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
            self._fen_update(pos, 1)
            _list = _lists[pos]
            _list.insert(idx, value)
            _list_lens[pos] += 1
            if _load + _load < len(_list):
                _lists.insert(pos + 1, _list[_load:])
                _list_lens.insert(pos + 1, len(_list) - _load)
                _list_lens[pos] = _load
                del _list[_load:]
                self._rebuild = True
        else:
            _lists.append([value])
            _list_lens.append(1)
            self._rebuild = True
        self._len += 1

    def __iter__(self):
        """Return an iterator over the sorted list."""
        return (value for _list in self._lists for value in _list)

    def __reversed__(self):
        """Return a reverse iterator over the sorted list."""
        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):
        """Return string representation of sorted list."""
        return "SortedList({0})".format(list(self))

def solve(N, M, queries):
    idToMark = [-1 for i in range(N)]
    cups = UnsortedList([i for i in range(N)])
    for mark, pos in queries:
        pos -= 1  # 0-indexed
        cupId = cups[pos]
        del cups[pos]
        cups.insert(0, cupId)

        if idToMark[cupId] == -1:
            idToMark[cupId] = mark
        elif idToMark[cupId] != mark:
            return b"-1"

    markToCounts = [0 for i in range(N + 1)]
    for cupId, mark in enumerate(idToMark):
        if mark != -1:
            markToCounts[mark] += 1
            if markToCounts[mark] > 1:
                return b"-1"

    j = 1
    ans = []
    for cupId, mark in enumerate(idToMark):
        if mark != -1:
            ans.append(mark)
        else:
            while markToCounts[j] > 0:
                j += 1
            ans.append(j)
            j += 1
    return b" ".join(str(x).encode("ascii") for x in ans)

if False:
    N, M = 10 ** 6, 10 ** 6
    queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)]
    ans = solve(N, M, queries)
    # print(ans)
    assert ans != b"-1"
    exit()

if __name__ == "__main__":
    input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

    N, M = [int(x) for x in input().split()]
    queries = ((int(x) for x in input().split()) for i in range(M))
    ans = solve(N, M, queries)

    os.write(1, ans)

```


447_B. DZY Loves Strings

DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where

<image>

Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?

Input

The first line contains a single string s (1 ≤ |s| ≤ 103).

The second line contains a single integer k (0 ≤ k ≤ 103).

The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.

Output

Print a single integer — the largest possible value of the resulting string DZY could get.

Examples

Input

abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Output

41

Note

In the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41.

```python
s = input()
k = int(input())
w = list(map(int, input().split()))
value = 0
for i in range(len(s)):
  value += (i + 1) * w[ord(s[i]) - ord('a')]
for i in range(len(s) + 1, len(s) + k + 1):
  value += max(w) * i
print(value)
```


469_C. 24 Game

Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.

Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a × b.

After n - 1 steps there is only one number left. Can you make this number equal to 24?

Input

The first line contains a single integer n (1 ≤ n ≤ 105).

Output

If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).

If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.

If there are multiple valid answers, you may print any of them.

Examples

Input

1

Output

NO

Input

8

Output

YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24


491_B. New York Hotel

Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.

Suppose that the distance between neighboring crossings are all the same equal to one kilometer.

Input

The first line contains two integers N и M — size of the city (1 ≤ N, M ≤ 109). In the next line there is a single integer C (1 ≤ C ≤ 105) — the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 ≤ x ≤ N, 1 ≤ y ≤ M). The next line contains an integer H — the number of restaurants (1 ≤ H ≤ 105). Following H lines contain descriptions of restaurants in the same format.

Several restaurants and hotels may be located near the same crossing.

Output

In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.

Examples

Input

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

Output

6
2

```python
N, M = input().split()
a, b, c, d = [int(1e10) for _ in range(4)]
for i in range(int(input())):
    x, y = list(map(int, input().split()))
    a, b, c, d = min(a, x + y), min(b, x - y), min(c, - x + y), min(d, - x - y)
res, pos = int(1e10), 0
for i in range(int(input())):
    x, y = list(map(int, input().split()))
    ans = max(max(x + y - a, x - y - b), max( - x + y - c, - x - y - d))
    if ans < res:
        pos = i + 1
        res = ans
print(res, pos, sep = '\n')
```


515_C. Drazil and Factorial

Drazil is playing a math game with Varda.

Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.

First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:

1. x doesn't contain neither digit 0 nor digit 1.

2. <image> = <image>.

Help friends find such number.

Input

The first line contains an integer n (1 ≤ n ≤ 15) — the number of digits in a.

The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.

Output

Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.

Examples

Input

4
1234

Output

33222

Input

3
555

Output

555

Note

In the first case, <image>

```python
#in the name of god
#Mr_Rubik
#CodeForces,Problemset
sepData=[[],[],[2],[3],[2,2,3],[5],[5,3],[7],[7,2,2,2],[7,2,3,3]]
digit=input()
number=input()
ans=[]
for i in number:
    if i!='1' and i!='\r':
        for j in sepData[int(i)]:
            ans.append(j)
ans.sort(reverse=True)
for i in ans:
    print(i,end="")
```


590_C. Three States

The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.

Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.

Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.

It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.

Input

The first line of the input contains the dimensions of the map n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns respectively.

Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.

Output

Print a single integer — the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.

Examples

Input

4 5
11..2
#..22
#.323
.#333

Output

2

Input

1 5
1#2#3

Output

-1

```python
# lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje
from collections import deque
n, m = input().split()
n = int(n)
m = int(m)

def idx(i, j):
    return i*m + j

max = n*m*2
graph = ""
virtDist = [[], [], []]
virtVertex = [deque(), deque(), deque()]
virtNodesDst = [max, max, max]
code = ord("1")
for i in range(0, n):
    s = input()
    graph += s
    for j in range(0, m):
        virtDist[0].append(max)
        virtDist[1].append(max)
        virtDist[2].append(max)
        indx = ord(s[j])-code
        if 0 > indx or indx > 2:
            continue
        virtVertex[indx].append((i, j))
        i2 = idx(i, j)
        virtDist[indx][-1] = 0

def bfs01(queue, distance):
    while queue:
        pi, pj = queue.popleft()
        for i, j in [(pi, pj-1), (pi, pj+1), (pi-1, pj), (pi+1, pj)]:
            indx = idx(i, j)
            if 0 > i or i >= n or 0 > j or j >= m or graph[indx] == '#':
                continue
            isRoad = graph[indx] == "."
            newDistance = distance[idx(pi, pj)] + (1 if isRoad else 0)
            if distance[indx] > newDistance:  # relax
                distance[indx] = newDistance
                if isRoad:
                    queue.append((i, j))
                else:
                    queue.appendleft((i, j))

bfs01(virtVertex[0], virtDist[0])
bfs01(virtVertex[1], virtDist[1])
bfs01(virtVertex[2], virtDist[2])

output = max
for i in range(0, n*m):
    output = min(virtDist[0][i] + virtDist[1][i] + virtDist[2]
                 [i] - (2 if graph[i] == "."else 0), output)

print(output if output < max else -1)

```


612_B. HDD is Outdated Technology

HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.

One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.

Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 ≤ fi ≤ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.

It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.

Input

The first line contains a positive integer n (1 ≤ n ≤ 2·105) — the number of fragments.

The second line contains n different integers fi (1 ≤ fi ≤ n) — the number of the fragment written in the i-th sector.

Output

Print the only integer — the number of time units needed to read the file.

Examples

Input

3
3 1 2

Output

3

Input

5
1 3 5 4 2

Output

10

Note

In the second example the head moves in the following way:

  * 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
  * 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
  * 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
  * 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units

So the answer to the second example is 4 + 3 + 2 + 1 = 10.

```python
n = int(input())
fi = list(map(int, input().split()))
fi2 = list(range(n))
i = 0
while i < n:
  fi2[fi[i] - 1] = i
  i += 1
pos = fi2[0]
i = 1
d = 0
while i < n:
  d += abs(fi2[i] - pos)
  pos = fi2[i]
  i += 1
print(d)

```


632_B. Alice, Bob, Two Teams

Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.

The way to split up game pieces is split into several steps:

  1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
  2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
  3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.

The strength of a player is then the sum of strengths of the pieces in the group.

Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.

Input

The first line contains integer n (1 ≤ n ≤ 5·105) — the number of game pieces.

The second line contains n integers pi (1 ≤ pi ≤ 109) — the strength of the i-th piece.

The third line contains n characters A or B — the assignment of teams after the first step (after Alice's step).

Output

Print the only integer a — the maximum strength Bob can achieve.

Examples

Input

5
1 2 3 4 5
ABABA

Output

11

Input

5
1 2 3 4 5
AAAAA

Output

15

Input

1
1
B

Output

1

Note

In the first sample Bob should flip the suffix of length one.

In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.

In the third sample Bob should do nothing.

```python
read = lambda: map(int, input().split())
n = int(input())
p = list(read())
a = [{'B': 1, 'A': 0}[i] for i in input()]
cur = sum(p[i] for i in range(n) if a[i])
ans = cur
b = a[:]
for i in range(n):
    b[i] = int(not a[i])
    if b[i]: cur += p[i]
    else: cur -= p[i]
    ans = max(ans, cur)
cur = sum(p[i] for i in range(n) if a[i])
b = a[:]
for i in range(n - 1, -1, -1):
    b[i] = int(not a[i])
    if b[i]: cur += p[i]
    else: cur -= p[i]
    ans = max(ans, cur)
print(ans)

```


660_E. Different Subsets For All Tuples

For a sequence a of n integers between 1 and m, inclusive, denote f(a) as the number of distinct subsequences of a (including the empty subsequence).

You are given two positive integers n and m. Let S be the set of all sequences of length n consisting of numbers from 1 to m. Compute the sum f(a) over all a in S modulo 109 + 7.

Input

The only line contains two integers n and m (1 ≤ n, m ≤ 106) — the number of elements in arrays and the upper bound for elements.

Output

Print the only integer c — the desired sum modulo 109 + 7.

Examples

Input

1 3

Output

6

Input

2 2

Output

14

Input

3 3

Output

174


707_C. Pythagorean Triples

Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.

For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.

Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.

Katya had no problems with completing this task. Will you do the same?

Input

The only line of the input contains single integer n (1 ≤ n ≤ 109) — the length of some side of a right triangle.

Output

Print two integers m and k (1 ≤ m, k ≤ 1018), such that n, m and k form a Pythagorean triple, in the only line.

In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.

Examples

Input

3

Output

4 5

Input

6

Output

8 10

Input

1

Output

-1

Input

17

Output

144 145

Input

67

Output

2244 2245

Note

<image>

Illustration for the first sample.


750_A. New Year and Hurry

Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th problem.

Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs k minutes to get there from his house, where he will participate in the contest first.

How many problems can Limak solve if he wants to make it to the party?

Input

The only line of the input contains two integers n and k (1 ≤ n ≤ 10, 1 ≤ k ≤ 240) — the number of the problems in the contest and the number of minutes Limak needs to get to the party from his house.

Output

Print one integer, denoting the maximum possible number of problems Limak can solve so that he could get to the party at midnight or earlier.

Examples

Input

3 222

Output

2

Input

4 190

Output

4

Input

7 1

Output

7

Note

In the first sample, there are 3 problems and Limak needs 222 minutes to get to the party. The three problems require 5, 10 and 15 minutes respectively. Limak can spend 5 + 10 = 15 minutes to solve first two problems. Then, at 20:15 he can leave his house to get to the party at 23:57 (after 222 minutes). In this scenario Limak would solve 2 problems. He doesn't have enough time to solve 3 problems so the answer is 2.

In the second sample, Limak can solve all 4 problems in 5 + 10 + 15 + 20 = 50 minutes. At 20:50 he will leave the house and go to the party. He will get there exactly at midnight.

In the third sample, Limak needs only 1 minute to get to the party. He has enough time to solve all 7 problems.

```python
def main():
    n,m = [int(v) for v in input().split()]
    e = 4*60-m
    d = 0
    i = 1
    while d<=e:
        d+=5*(i)
        if d>e:
            break
        i+=1

    print(min(n,i-1))

if __name__ == "__main__":
    main()

```


798_D. Mike and distribution

Mike has always been thinking about the harshness of social inequality. He's so obsessed with it that sometimes it even affects him while solving problems. At the moment, Mike has two sequences of positive integers A = [a1, a2, ..., an] and B = [b1, b2, ..., bn] of length n each which he uses to ask people some quite peculiar questions.

To test you on how good are you at spotting inequality in life, he wants you to find an "unfair" subset of the original sequence. To be more precise, he wants you to select k numbers P = [p1, p2, ..., pk] such that 1 ≤ pi ≤ n for 1 ≤ i ≤ k and elements in P are distinct. Sequence P will represent indices of elements that you'll select from both sequences. He calls such a subset P "unfair" if and only if the following conditions are satisfied: 2·(ap1 + ... + apk) is greater than the sum of all elements from sequence A, and 2·(bp1 + ... + bpk) is greater than the sum of all elements from the sequence B. Also, k should be smaller or equal to <image> because it will be to easy to find sequence P if he allowed you to select too many elements!

Mike guarantees you that a solution will always exist given the conditions described above, so please help him satisfy his curiosity!

Input

The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the sequences.

On the second line there are n space-separated integers a1, ..., an (1 ≤ ai ≤ 109) — elements of sequence A.

On the third line there are also n space-separated integers b1, ..., bn (1 ≤ bi ≤ 109) — elements of sequence B.

Output

On the first line output an integer k which represents the size of the found subset. k should be less or equal to <image>.

On the next line print k integers p1, p2, ..., pk (1 ≤ pi ≤ n) — the elements of sequence P. You can print the numbers in any order you want. Elements in sequence P should be distinct.

Example

Input

5
8 7 4 8 3
4 2 5 3 7

Output

3
1 4 5

```python
n = int(input())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
idAB = zip(range(n), A, B)
idAB = sorted(idAB, key=lambda x: x[1], reverse=True)
ans = [idAB[0][0] + 1]
i = 1
while i < n:
        choice = max(idAB[i:i + 2], key=lambda x: x[2])
        ans.append(choice[0] + 1)
        i += 2

ans = sorted(ans)
print(len(ans))
print(*ans)

```


818_F. Level Generation

Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.

Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph.

So the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops.

Input

The first line of input file contains a positive integer q (1 ≤ q ≤ 100 000) — the number of graphs Ivan needs to construct.

Then q lines follow, i-th line contains one positive integer ni (1 ≤ ni ≤ 2·109) — the number of vertices in i-th graph.

Note that in hacks you have to use q = 1.

Output

Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph.

Example

Input

3
3
4
6

Output

2
3
6

Note

In the first example it is possible to construct these graphs:

  1. 1 - 2, 1 - 3;
  2. 1 - 2, 1 - 3, 2 - 4;
  3. 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6.

```python
#! /usr/bin/env python

# http://codeforces.com/problemset/problem/818/F
# Problem name ::: F. Level Generation
# submission number

#212055293
#508427854

def newest_approach(n):
    from math import floor, ceil, sqrt

    quad_solv = sqrt(2*n+1/4)-1/2
    x = floor(quad_solv)
    y = ceil(quad_solv)

    xed = int(x*(x-1)/2 + n - x)
    xbr = n - x

    ybr = n - y
    yed = 2*ybr

    if xed > yed:
        print(xed)
        # print("nodes = %s :: edges = %s :: bridges = %s" % (n, xed, xbr))
    else:
        print(yed)
        # print("nodes = %s :: edges = %s :: bridges = %s" % (n, yed, ybr))

    return

def main():

    import sys

    data = [line.rstrip() for line in sys.stdin.readlines()]
    num_graphs = data[0]
    graph_sizes = [int(x) for x in data[1:]]

    for val in graph_sizes:
        # binary_search(val)
        # new_approach(val)
        newest_approach(val)

if __name__ == '__main__':
    main()

```


844_B. Rectangles

You are given n × m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that:

  1. All cells in a set have the same color.
  2. Every two cells in a set share row or column.

Input

The first line of input contains integers n and m (1 ≤ n, m ≤ 50) — the number of rows and the number of columns correspondingly.

The next n lines of input contain descriptions of rows. There are m integers, separated by spaces, in each line. The number equals 0 if the corresponding cell is colored white and equals 1 if the corresponding cell is colored black.

Output

Output single integer — the number of non-empty sets from the problem description.

Examples

Input

1 1
0

Output

1

Input

2 3
1 0 1
0 1 0

Output

8

Note

In the second example, there are six one-element sets. Additionally, there are two two-element sets, the first one consists of the first and the third cells of the first row, the second one consists of the first and the third cells of the second row. To sum up, there are 8 sets.

```python
from math import factorial

def count(n, k):
    return factorial(n) // (factorial(k) * factorial(n - k))

n, m = map(int, input().split())
table = []
for i in range(n):
    table.append(list(map(int, input().split())))
ans = 0
for i in range(n):
    c0 = table[i].count(0)
    c1 = table[i].count(1)
    for j in range(1, c0 + 1):
        ans += count(c0, j)
    for j in range(1, c1 + 1):
        ans += count(c1, j)
for j in range(m):
    c0 = 0
    c1 = 0
    for i in range(n):
        if table[i][j] == 0:
            c0 += 1
        else:
            c1 += 1
    for i in range(2, c0 + 1):
        ans += count(c0, i)
    for i in range(2, c1 + 1):
        ans += count(c1, i)
print(ans)
```


864_E. Fire

Polycarp is in really serious trouble — his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di — the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti ≥ di, then i-th item cannot be saved.

Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b — in ta + tb seconds after fire started.

Input

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of items in Polycarp's house.

Each of the following n lines contains three integers ti, di, pi (1 ≤ ti ≤ 20, 1 ≤ di ≤ 2 000, 1 ≤ pi ≤ 20) — the time needed to save the item i, the time after which the item i will burn completely and the value of item i.

Output

In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m — the number of items in the desired set. In the third line print m distinct integers — numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them.

Examples

Input

3
3 7 4
2 6 5
3 7 6

Output

11
2
2 3

Input

2
5 6 1
3 3 5

Output

1
1
1

Note

In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11.

In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time.

```python
from sys import stdin, stdout

n = int(stdin.readline())
items = []
for i in range(n):
  t,d,p = map(int,stdin.readline().split())
  items.append((d,p,t,i+1))
items.sort()

N = 2000+1
dp = [0 for i in range(N)]
cur = [[] for i in range(N)]
for d,p,t,it in items:
  for i in range(d-1,t-1,-1):
    if dp[i-t] + p > dp[i]:
      dp[i] = dp[i-t] + p
      cur[i] = cur[i-t] + [it]

best = 0
for i in range(N):
  if dp[i] > dp[best]:
    best = i

stdout.write('{}\n'.format(dp[best]))
stdout.write('{}\n'.format(len(cur[best])))
stdout.write(' '.join([str(x) for x in cur[best]]) + '\n')

```


88_D. Vasya and Types

Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.

There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type X — that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of X, which is a pointer, you can add an ampersand — that will result in a type &X, to which refers X. That is called a dereference operation.

The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof.

  * The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
  * The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.

An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.

Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.

Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T *  is always equal to T.

Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).

Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.

Input

The first line contains an integer n (1 ≤ n ≤ 100) — the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.

All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.

Output

For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.

Examples

Input

5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv

Output

void*
errtype
void

Input

17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c

Output

void*
void**
void
void**
errtype
void
errtype
errtype
errtype

Note

Let's look at the second sample.

After the first two queries typedef the b type is equivalent to void*, and с — to void**.

The next query typedef redefines b — it is now equal to &b = &void* = void. At that, the с type doesn't change.

After that the с type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.

Then the b type is again redefined as &void = errtype.

Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.

```python
types = {'void':'void', 'errtype':'errtype'}

def getRealType(type_expr):
  expr_type = type_expr.strip('&*')
  full_type_name = type_expr.replace(expr_type, types.get(expr_type, "errtype"))
  base_type = full_type_name.strip('&*')
  if base_type == "void":
    addr_count = full_type_name.count('*')
    deref_count = full_type_name.count('&')
    if deref_count > addr_count:
      return "errtype"
    return base_type + "*" * (addr_count - deref_count)
  else:
    return "errtype"

def setTypeAlias(type_expr, alias_name):
  types[alias_name] = getRealType(type_expr)

n = int(input())
for _ in range(n):
  operator = input().split()
  command = operator[0]
  if command == "typedef":
    setTypeAlias(operator[1], operator[2])
  else:
    print(getRealType(operator[1]))
```


913_B. Christmas Spruce

Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.

Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.

The definition of a rooted tree can be found [here](https://goo.gl/1dqvzz).

Input

The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i).

Vertex 1 is the root. It's guaranteed that the root has at least 2 children.

Output

Print "Yes" if the tree is a spruce and "No" otherwise.

Examples

Input

4
1
1
1

Output

Yes

Input

7
1
1
1
2
2
2

Output

No

Input

8
1
1
1
1
3
3
3

Output

Yes

Note

The first example:

<image>

The second example:

<image>

It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.

The third example:

<image>

```python
if __name__ == '__main__':
    n = int(input())
    nonleaf = [0 for i in range(1010)]
    child = [[] for i in range(1010)]
    leaf = [0 for i in range(1010)]

    def dfs(s):
        cnt = 0
        for chd in child[s]:
            cnt += dfs(chd)
        leaf[s] = cnt
        return 1 - nonleaf[s]

    for i in range(2, n + 1):
        node = int(input())
        child[node].append(i)
        nonleaf[node] = 1

    dfs(1)

    # print(nonleaf[1:n + 1])
    # print(child[1:n + 1])
    # print(leaf[1:n + 1])

    for i in range(1, n + 1):
        if nonleaf[i] and leaf[i] < 3:
            print("No")
            exit()

    print("Yes")

```


935_B. Fafa and the Gates

Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.

The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation x = y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0, 0), (1, 1), (2, 2), ...). The wall and the gates do not belong to any of the kingdoms.

Fafa is at the gate at position (0, 0) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from (x, y) to (x, y + 1)) and 'R' (move one step right, from (x, y) to (x + 1, y)).

Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point (0, 0), i. e. he is initially on the side he needs.

Input

The first line of the input contains single integer n (1 ≤ n ≤ 105) — the number of moves in the walking sequence.

The second line contains a string S of length n consisting of the characters 'U' and 'R' describing the required moves. Fafa will follow the sequence S in order from left to right.

Output

On a single line, print one integer representing the number of silver coins Fafa needs to pay at the gates to follow the sequence S.

Examples

Input

1
U

Output

0

Input

6
RURUUR

Output

1

Input

7
URRRUUU

Output

2

Note

The figure below describes the third sample. The red arrows represent the sequence of moves Fafa will follow. The green gates represent the gates at which Fafa have to pay silver coins.

<image>

```python
n=int(input())
s=input()
x=0
y=0
c=0
side=2
lastside=2
for i in s:
    prevx=x
    prevy=y
    if i=='U':
        y+=1
    if i=='R':
        x+=1
    lastside=side
    if x>y:
        side=0
    elif x<y:
        side=1
    if lastside!=side and lastside!=2:
        c+=1
print(c)
```


961_A. Tetris

You are given a following process.

There is a platform with n columns. 1 × 1 squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column.

When all of the n columns have at least one square in them, the bottom row is being removed. You will receive 1 point for this, and all the squares left will fall down one row.

You task is to calculate the amount of points you will receive.

Input

The first line of input contain 2 integer numbers n and m (1 ≤ n, m ≤ 1000) — the length of the platform and the number of the squares.

The next line contain m integer numbers c_1, c_2, ..., c_m (1 ≤ c_i ≤ n) — column in which i-th square will appear.

Output

Print one integer — the amount of points you will receive.

Example

Input

3 9
1 1 2 2 2 3 1 2 3

Output

2

Note

In the sample case the answer will be equal to 2 because after the appearing of 6-th square will be removed one row (counts of the squares on the platform will look like [2~ 3~ 1], and after removing one row will be [1~ 2~ 0]).

After the appearing of 9-th square counts will be [2~ 3~ 1], and after removing one row it will look like [1~ 2~ 0].

So the answer will be equal to 2.

```python
n, m = map(int, input().split())
mas = list(map(int, input().split()))
mn = 1001
for i in range(1, n + 1):
    if mas.count(i) < mn:
        mn = mas.count(i)
print(mn)
```


988_F. Rain and Umbrellas

Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second.

Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≤ l_i < r_i ≤ a).

There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≤ x_i ≤ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas.

During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≤ x and x + 1 ≤ r_i).

The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.

Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.

Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally.

Input

The first line contains three integers a, n and m (1 ≤ a, m ≤ 2000, 1 ≤ n ≤ ⌈a/2⌉) — the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas.

Each of the next n lines contains two integers l_i and r_i (0 ≤ l_i < r_i ≤ a) — the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i.

Each of the next m lines contains two integers x_i and p_i (0 ≤ x_i ≤ a, 1 ≤ p_i ≤ 10^5) — the location and the weight of the i-th umbrella.

Output

Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer — the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally.

Examples

Input

10 2 4
3 7
8 10
0 10
3 4
8 1
1 2

Output

14

Input

10 1 1
0 9
0 5

Output

45

Input

10 1 1
0 9
1 5

Output

-1

Note

In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14).

In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end.

```python
import sys
a,m,n=list(map(int,input().split()))
aux=[0]*(a+1)
inf=10**15
dp=[aux.copy() for i in range(n+1)]
m1=10**12
m2=10**12
for i in range(m):
    l,r=list(map(int,input().split()))
    if l<m1:
        m1=l
    for j in range(l,r):
        dp[0][j+1]=inf
s=[]
for i in range(1,n+1):
    x,w=list(map(int,input().split()))
    s.append(tuple([x,w]))
    if x<m2:
        m2=x
if m2>m1:
    print(-1)
    sys.exit()
s.sort()

for i in range(1,n+1):
    x=s[i-1][0]
    w=s[i-1][1]
    for j in range(x+1):
        dp[i][j]=dp[i-1][j]
    for j in range(x+1,a+1):
        if i!=1:
            dp[i][j]=min(dp[0][j]+dp[i][j-1],dp[i-1][j],w*(j-x)+dp[i][x])
        else:
            dp[i][j]=min(dp[0][j]+dp[i][j-1],w*(j-x)+dp[i][x])

ans=dp[-1][-1]
if ans>=inf:
    print(-1)
else:
    print(ans)

```


p02598 AtCoder Beginner Contest 174 - Logs

We have N logs of lengths A_1,A_2,\cdots A_N.

We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.

Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.

Constraints

* 1 \leq N \leq 2 \times 10^5
* 0 \leq K \leq 10^9
* 1 \leq A_i \leq 10^9
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print an integer representing the answer.

Examples

Input

2 3
7 9

Output

4

Input

3 0
3 4 5

Output

5

Input

10 10
158260522 877914575 602436426 24979445 861648772 623690081 433933447 476190629 262703497 211047202

Output

292638192

```python
n,k = map(int,input().split())
l = list(map(int,input().split()))
l.sort()
x,y=0,10**9
while y>x+1:
    m = (x+y)//2
    c=0
    for i in l:
        c+=(i-1)//m
    if c<=k:
        y=m
    else:
        x=m
print(y)
```


p02729 AtCoder Beginner Contest 159 - The Number of Even Pairs

We have N+M balls, each of which has an integer written on it.
It is known that:

* The numbers written on N of the balls are even.
* The numbers written on M of the balls are odd.

Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.
It can be shown that this count does not depend on the actual values written on the balls.

Constraints

* 0 \leq N,M \leq 100
* 2 \leq N+M
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the answer.

Examples

Input

2 1

Output

1

Input

4 3

Output

9

Input

1 1

Output

0

Input

13 3

Output

81

Input

0 3

Output

3