p01035 Hard Beans

Problem

Beans are popular at Otsu University. N beans are lined up in a straight line. Each is numbered from 0 to N-1, and the hardness of the i-th bean is ai.

Cyan considers the ideal bean hardness to be D. However, Cyan doesn't want to go get the beans that are too far away because he is troublesome. Therefore, Cyan wants to know the beans whose hardness is closest to D among the l-th to r-th beans.

Cyan asks Q questions, so create a program to find the minimum value of | bean hardness − D | in the closed interval [l, r] for each question. (However, | a | represents the absolute value of a.)

Constraints

The input satisfies the following constraints.

* 1 ≤ N ≤ 105
* 0 ≤ | ai | ≤ 106 (0 ≤ i ≤ N−1)
* 1 ≤ Q ≤ 105
* 0 ≤ Di ≤ 106
* 0 ≤ li ≤ ri ≤ N-1

Input

The input is given in the following format.

N
a0 a1 ... aN−1
Q
l0 r0 D0
l1 r1 D1
..
..
..
lQ−1 rQ−1 DQ−1

The first line is given one integer N. On the second line, N integers are given, separated by blanks. On the third line, the number of queries is given as one integer Q. The query values l, r, and D are given in the following 4 to 3 + Q lines.

Output

For each query, output the absolute value of the difference between D and the hardness of the bean closest to hardness D among the [l, r] th beans on one line.

Examples

Input

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

Output

0
1
1

Input

10
4 5 0 21 9 100 12 9 0 8
5
0 3 20
2 5 100
8 9 9
5 5 10
0 9 20

Output

1
0
1
90
1

```python

class SegmentTree(object):
    def __init__(self, a:list, default: int, op):
        from math import ceil, log
        real_size = len(a)
        self.elem_size = elem_size = 1<<ceil(log(real_size, 2))
        self.tree = tree = [default] * (elem_size * 2)
        tree[elem_size:elem_size + real_size] = a
        self.default = default
        self.op = op
        for i in range(elem_size - 1, 0, -1):
            tree[i] = op(tree[i<<1], tree[(i<<1)+1])
    def get_value(self, x:int, y:int):
        l, r = x+self.elem_size, y+self.elem_size
        tree, result, op = self.tree, self.default, self.op
        while l<r:
            if l & 1:
                result = op(tree[l], result)
                l += 1
            if r&1:
                r -= 1
                result = op(tree[r], result)
            l, r = l>>1, r>>1
        return result
    def set_value(self, i:int, value:int):
        k = self.elem_size + i
        self.tree[k] = value
        self.update(k)
    def update(self, i:int):
        op, tree = self.op, self.tree
        while i > 1:
            i >>= 1
            tree[i] = op(tree[i<<1], tree[(i<<1)+1])

N = int(input())
A = list(map(int, input().split()))
Q_ = int(input())
Q = []
for i in range(Q_):
    l, r, d = map(int, input().split())
    Q.append([l, r, d, i])
seg1 = SegmentTree([-1<<30]*N, -1<<30, max)
seg2 = SegmentTree(A, 1<<30, min)
from operator import itemgetter
Q.sort(key=itemgetter(2))
A = sorted(zip(A, range(N)), key=itemgetter(0))

a_idx = 0
Ans = [0] * Q_
for l, r, d, q_idx in Q:
    while a_idx < N:
        a0, a1 = A[a_idx]
        if a0 > d:
            break
        else:
            seg1.set_value(a1, a0)
            seg2.set_value(a1, 1<<30)
            a_idx += 1
    an1 = abs(seg1.get_value(l, r+1) - d)
    an2 = abs(seg2.get_value(l, r+1) - d)
    Ans[q_idx] = min(an1, an2)

print(*Ans, sep="\n")

```


p01634 Register Phase

It is important to use strong passwords to make the Internet more secure. At the same time, it is very important not to reuse the same password. No matter how strong your password is, if the plaintext is leaked in one place, it will be very easy to break. Of course, if all applications hash passwords and use SALT properly, such damage will not occur even if leaked, but there are still applications that store passwords in clear text.

Well, the contest is about to begin. I have to register a team account ...

problem

A string representing the password is given. Check if the character string meets all of the following conditions, and if it meets all of the following conditions, output "VALID", and if there is an item that does not meet even one, output "INVALID".

* String length is 6 or more
* Contains one or more numbers
* Contains one or more uppercase letters
* Contains one or more lowercase letters

input

A string representing the password is given on one line.

output

Print "VALID" if the password string meets all the conditions in question, and "INVALID" if there are conditions that do not.

Constraint

* The password string must be between 1 and 20 characters.
* Password string contains only uppercase letters, lowercase letters, and numbers

Input / output example

Input 1

password

Output 1

INVALID

It is a password that is widely used all over the world.

Input 2

AizuCamp2013

Output 2

VALID

Great password.

Input 3

1234

Output 3

INVALID

Widely used as a PIN.

Input 4

NaBiO3

Output 4

VALID

It is barely 6 characters or more.

Example

Input

password

Output

INVALID

```python
A=0
n=str(input())
if len(n)>=6:
    A=A+1
B=n.count('0')+n.count('1')+n.count('2')+n.count('3')+n.count('4')+n.count('5')+n.count('6')+n.count('7')+n.count('8')+n.count('9')
if B>0:
    A=A+1
C=n.count('a')+n.count('b')+n.count('c')+n.count('d')+n.count('e')+n.count('f')+n.count('g')+n.count('h')+n.count('i')+n.count('j')+n.count('k')+n.count('l')+n.count('m')+n.count('n')+n.count('o')+n.count('p')+n.count('q')+n.count('r')+n.count('s')+n.count('t')+n.count('u')+n.count('v')+n.count('w')++n.count('x')+n.count('y')+n.count('z')
if C>0:
    A=A+1
D=n.count('A')+n.count('B')+n.count('C')+n.count('D')+n.count('E')+n.count('F')+n.count('G')+n.count('H')+n.count('I')+n.count('J')+n.count('K')+n.count('L')+n.count('M')+n.count('N')+n.count('O')+n.count('P')+n.count('Q')+n.count('R')+n.count('S')+n.count('T')+n.count('U')+n.count('V')+n.count('W')++n.count('X')+n.count('Y')+n.count('Z')
if D>0:
    A=A+1
if A==4:
    print('VALID')
else:
    print('INVALID')

```


p02201 Ninja E869120

Increasing E869120 (Ninja E869120)

E869120 You are good at alter ego.

Here are $ N $ members of the PA Lab. But some of them may be E869120.

So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.

E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.

input

Input is given from standard input in the following format.

$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $

output

E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".

However, insert a line break at the end.

Constraint

* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.

Input example 1

Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO

Output example 1

2

E869120 You are split into two.

Input example 2

3
SQUARE1001
MENCOTTON
B2563125

Output example 2

0

E869120 Please output 0 when you are not there.

Input example 3

6
E8691200
E869121
E869122
E869123
E869124
E869125

Output example 3

0

Beware of impostors.

Example

Input

5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO

Output

2

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

N=int(input())
ANS=0
for i in range(N):
    if input().strip()=="E869120":
        ANS+=1
print(ANS)

```


p02355 The Smallest Window II

For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $K$, find the smallest sub-array size (smallest window length) where the elements in the sub-array contains all integers in range [$1, 2, ..., K$]. If there is no such sub-array, report 0.

Constraints

* $1 \leq N \leq 10^5$
* $1 \leq K \leq 10^5$
* $1 \leq a_i \leq 10^5$

Input

The input is given in the following format.

$N$ $K$
$a_1$ $a_2$ ... $a_N$

Output

Print the smallest sub-array size in a line.

Examples

Input

6 2
4 1 2 1 3 5

Output

2

Input

6 3
4 1 2 1 3 5

Output

3

Input

3 4
1 2 3

Output

0

```python
class SegmentTree():
    def __init__(self, arr, func=min, ie=2**63):
        self.h = (len(arr) - 1).bit_length()
        self.n = 2**self.h
        self.ie = ie
        self.func = func
        self.tree = [ie for _ in range(2 * self.n)]
        for i in range(len(arr)):
            self.tree[self.n + i] = arr[i]
        for i in range(1, self.n)[::-1]:
            self.tree[i] = func(self.tree[2 * i], self.tree[2 * i + 1])

    def set(self, idx, x):
        idx += self.n
        self.tree[idx] = x
        while idx:
            idx >>= 1
            self.tree[idx] = self.func(self.tree[2 * idx], self.tree[2 * idx + 1])

    def query(self, lt, rt):
        lt += self.n
        rt += self.n
        vl = vr = self.ie
        while rt - lt > 0:
            if lt & 1:
                vl = self.func(vl, self.tree[lt])
                lt += 1
            if rt & 1:
                rt -= 1
                vr = self.func(self.tree[rt], vr)
            lt >>= 1
            rt >>= 1
        return self.func(vl, vr)

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

res = N + 1
st = SegmentTree([0] * K)
rt = 0

for lt in range(N):
    while rt < N and st.tree[1] == 0:
        if A[rt] <= K:
            st.set(A[rt] - 1, st.query(A[rt] - 1, A[rt]) + 1)
        rt += 1
    if st.tree[1] != 0:
        res = min(res, rt - lt)
    if A[lt] <= K:
        st.set(A[lt] - 1, st.query(A[lt] - 1, A[lt]) - 1)

print(res if res <= N else 0)

```


1040_A. Palindrome Dance

A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future.

On the day when the suits were to be bought, the director was told that the participants of the olympiad will be happy if the colors of the suits on the scene will form a palindrome. A palindrome is a sequence that is the same when read from left to right and when read from right to left. The director liked the idea, and she wants to buy suits so that the color of the leftmost dancer's suit is the same as the color of the rightmost dancer's suit, the 2nd left is the same as 2nd right, and so on.

The director knows how many burls it costs to buy a white suit, and how many burls to buy a black suit. You need to find out whether it is possible to buy suits to form a palindrome, and if it's possible, what's the minimal cost of doing so. Remember that dancers can not change positions, and due to bureaucratic reasons it is not allowed to buy new suits for the dancers who already have suits, even if it reduces the overall spending.

Input

The first line contains three integers n, a, and b (1 ≤ n ≤ 20, 1 ≤ a, b ≤ 100) — the number of dancers, the cost of a white suit, and the cost of a black suit.

The next line contains n numbers c_i, i-th of which denotes the color of the suit of the i-th dancer. Number 0 denotes the white color, 1 — the black color, and 2 denotes that a suit for this dancer is still to be bought.

Output

If it is not possible to form a palindrome without swapping dancers and buying new suits for those who have one, then output -1. Otherwise, output the minimal price to get the desired visual effect.

Examples

Input

5 100 1
0 1 2 1 2

Output

101

Input

3 10 12
1 2 0

Output

-1

Input

3 12 1
0 1 0

Output

0

Note

In the first sample, the cheapest way to obtain palindromic colors is to buy a black suit for the third from left dancer and a white suit for the rightmost dancer.

In the second sample, the leftmost dancer's suit already differs from the rightmost dancer's suit so there is no way to obtain the desired coloring.

In the third sample, all suits are already bought and their colors form a palindrome.

```python
def go():
    n, a, b = [int(i) for i in input().split(' ')]
    x = [int(i) for i in input().split(' ')]
    total = 0
    for i in range(n // 2):
        if (x[i] == 1 and x[n - 1 - i] == 0) or (x[i] == 0 and x[n - 1 - i] == 1):
            return -1
        elif x[i] == 2 and x[i] == x[n - 1 - i]:
            total += 2 * min(a, b)
        elif x[i] == 2:
            if x[n - i - 1] == 1:
                total += b
            else:
                total += a
        elif x[n - i - 1] == 2:
            if x[i] == 1:
                total += b
            else:
                total += a
    if n % 2 == 1 and x[n // 2] == 2:
        total += min(a, b)
    return total

print(go())

```


1063_A. Oh Those Palindromes

A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.

A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.

Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is 6 because all its substrings are palindromes, and the palindromic count of the string "abc" is 3 because only its substrings of length 1 are palindromes.

You are given a string s. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.

Input

The first line contains an integer n (1 ≤ n ≤ 100 000) — the length of string s.

The second line contains string s that consists of exactly n lowercase characters of Latin alphabet.

Output

Print string t, which consists of the same set of characters (and each characters appears exactly the same number of times) as string s. Moreover, t should have the maximum possible value of palindromic count among all such strings strings.

If there are multiple such strings, print any of them.

Examples

Input

5
oolol

Output

ololo

Input

16
gagadbcgghhchbdf

Output

abccbaghghghgdfd

Note

In the first example, string "ololo" has 9 palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.

In the second example, the palindromic count of string "abccbaghghghgdfd" is 29.

```python
n = int(input())
s = input()
k = {}

def choose(a, b):
    if b > a:
        return 0
    p = 1
    for i in range(b):
        p *= a - i
    for i in range(1, b + 1):
        p //= i
    return p

for i in range(n):
    if s[i] in k:
        k[s[i]] += 1
    else:
        k[s[i]] = 1
#print(k)
ans = 0
a = []
for i in k:
#    ans += k[i] + choose(k[i], 2)
    a.append(i*k[i])
print(''.join(a))

```


1104_C. Grid game

You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.

Input

The only line contains a string s consisting of zeroes and ones (1 ≤ |s| ≤ 1000). Zero describes vertical tile, one describes horizontal tile.

Output

Output |s| lines — for each tile you should output two positive integers r,c, not exceeding 4, representing numbers of smallest row and column intersecting with it.

If there exist multiple solutions, print any of them.

Example

Input

010

Output

1 1
1 2
1 4

Note

Following image illustrates the example after placing all three tiles:

<image> Then the first row is deleted:  <image>


1132_A. Regular Bracket Sequence

A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; "))" and ")((" are bracket sequences (but not regular ones), and "(a)" and "(1)+(1)" are not bracket sequences at all.

You have a number of strings; each string is a bracket sequence of length 2. So, overall you have cnt_1 strings "((", cnt_2 strings "()", cnt_3 strings ")(" and cnt_4 strings "))". You want to write all these strings in some order, one after another; after that, you will get a long bracket sequence of length 2(cnt_1 + cnt_2 + cnt_3 + cnt_4). You wonder: is it possible to choose some order of the strings you have such that you will get a regular bracket sequence? Note that you may not remove any characters or strings, and you may not add anything either.

Input

The input consists of four lines, i-th of them contains one integer cnt_i (0 ≤ cnt_i ≤ 10^9).

Output

Print one integer: 1 if it is possible to form a regular bracket sequence by choosing the correct order of the given strings, 0 otherwise.

Examples

Input

3
1
4
3

Output

1

Input

0
0
0
0

Output

1

Input

1
2
3
4

Output

0

Note

In the first example it is possible to construct a string "(())()(()((()()()())))", which is a regular bracket sequence.

In the second example it is possible to construct a string "", which is a regular bracket sequence.

```python
a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a == d:
  if a > 0 or c == 0:
    print(1)
  else:
    print(0)
else:
  print(0)
```


1152_D. Neko and Aki's Prank

Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys...

It took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of weird things, including a [trie](https://en.wikipedia.org/wiki/Trie) of all correct bracket sequences of length 2n.

The definition of correct bracket sequence is as follows:

  * The empty sequence is a correct bracket sequence,
  * If s is a correct bracket sequence, then (\,s ) is a correct bracket sequence,
  * If s and t are a correct bracket sequence, then st is also a correct bracket sequence.

For example, the strings "(())", "()()" form a correct bracket sequence, while ")(" and "((" not.

Aki then came up with an interesting problem: What is the size of the maximum matching (the largest set of edges such that there are no two edges with a common vertex) in this trie? Since the answer can be quite large, print it modulo 10^9 + 7.

Input

The only line contains a single integer n (1 ≤ n ≤ 1000).

Output

Print exactly one integer — the size of the maximum matching in the trie. Since the answer can be quite large, print it modulo 10^9 + 7.

Examples

Input

1

Output

1

Input

2

Output

3

Input

3

Output

9

Note

The pictures below illustrate tries in the first two examples (for clarity, the round brackets are replaced with angle brackets). The maximum matching is highlighted with blue.

<image> <image>


1174_B. Ehab Is an Odd Person

You're given an array a of length n. You can perform the following operation on it as many times as you want:

  * Pick two integers i and j (1 ≤ i,j ≤ n) such that a_i+a_j is odd, then swap a_i and a_j.

What is lexicographically the smallest array you can obtain?

An array x is [lexicographically smaller](https://en.wikipedia.org/wiki/Lexicographical_order) than an array y if there exists an index i such that x_i<y_i, and x_j=y_j for all 1 ≤ j < i. Less formally, at the first index i in which they differ, x_i<y_i

Input

The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of elements in the array a.

The second line contains n space-separated integers a_1, a_2, …, a_{n} (1 ≤ a_i ≤ 10^9) — the elements of the array a.

Output

The only line contains n space-separated integers, the lexicographically smallest array you can obtain.

Examples

Input

3
4 1 7

Output

1 4 7

Input

2
1 1

Output

1 1

Note

In the first example, we can swap 1 and 4 since 1+4=5, which is odd.

```python
n = eval(input())
a = list(map(int, input().split()))
odd = False
even = False
for i in range(n):
    if a[i] & 1:
        odd = True
    else:
        even = True
if odd & even:
    a.sort()
for x in a:
    print(x, end=" ")
```


1230_D. Marcin and Training Camp

Marcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.

Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i and b_i; b_i is equal to the skill level of the i-th student (the higher, the better). Also, there are 60 known algorithms, which are numbered with integers from 0 to 59. If the i-th student knows the j-th algorithm, then the j-th bit (2^j) is set in the binary representation of a_i. Otherwise, this bit is not set.

Student x thinks that he is better than student y if and only if x knows some algorithm which y doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.

Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?

Input

The first line contains one integer n (1 ≤ n ≤ 7000) — the number of students interested in the camp.

The second line contains n integers. The i-th of them is a_i (0 ≤ a_i < 2^{60}).

The third line contains n integers. The i-th of them is b_i (1 ≤ b_i ≤ 10^9).

Output

Output one integer which denotes the maximum sum of b_i over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.

Examples

Input

4
3 2 3 6
2 8 5 10

Output

15

Input

3
1 2 3
1 2 3

Output

0

Input

1
0
1

Output

0

Note

In the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of b_i.

In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.

```python
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
v = []
for i in range(n):
	v.append([a[i],b[i]])
v.sort()
prev = -1
big = []
flag = True
for i in v:
	if prev == i[0] and (flag or big[-1]!=i[0]):
		big.append(i[0])
		flag = False
	prev = i[0]
answer = 0
counter = 0
big.sort()
for i in v:
	for j in big:
		if j == (j|i[0]):
			answer += i[1]
			counter +=1
			break
if(counter<2):
	print(0)
else:
	print(answer)
```


1295_A. Display The Number

You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 10 decimal digits:

<image>

As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 1, you have to turn on 2 segments of the screen, and if you want to display 8, all 7 segments of some place to display a digit should be turned on.

You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than n segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than n segments.

Your program should be able to process t different test cases.

Input

The first line contains one integer t (1 ≤ t ≤ 100) — the number of test cases in the input.

Then the test cases follow, each of them is represented by a separate line containing one integer n (2 ≤ n ≤ 10^5) — the maximum number of segments that can be turned on in the corresponding testcase.

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

Output

For each test case, print the greatest integer that can be displayed by turning on no more than n segments of the screen. Note that the answer may not fit in the standard 32-bit or 64-bit integral data type.

Example

Input

2
3
4

Output

7
11

```python
import sys

def solution(n):
    if n % 2 == 0:
        print("1" * (n // 2))
    else:
        print("7" + "1" * (n // 2 - 1))

for line in sys.stdin:
    t = int(line)
    break

for line in sys.stdin:
    n = int(line)
    solution(n)

```


1316_A. Grade Allocation

n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students.

You can change each student's score as long as the following conditions are satisfied:

  * All scores are integers
  * 0 ≤ a_{i} ≤ m
  * The average score of the class doesn't change.

You are student 1 and you would like to maximize your own score.

Find the highest possible score you can assign to yourself such that all conditions are satisfied.

Input

Each test contains multiple test cases.

The first line contains the number of test cases t (1 ≤ t ≤ 200). The description of the test cases follows.

The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^{3}, 1 ≤ m ≤ 10^{5}) — the number of students and the highest possible score respectively.

The second line of each testcase contains n integers a_1, a_2, ..., a_n ( 0 ≤ a_{i} ≤ m) — scores of the students.

Output

For each testcase, output one integer — the highest possible score you can assign to yourself such that both conditions are satisfied._

Example

Input

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

Output

10
5

Note

In the first case, a = [1,2,3,4] , with average of 2.5. You can change array a to [10,0,0,0]. Average remains 2.5, and all conditions are satisfied.

In the second case, 0 ≤ a_{i} ≤ 5. You can change a to [5,1,1,3]. You cannot increase a_{1} further as it will violate condition 0≤ a_i≤ m.

```python
for i in range(int(input())):
    print(min(list(map(int, input().split()))[1], sum(list(map(int, input().split())))))

```


1337_C. Linova and Kingdom

Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.

<image>

There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.

As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.

A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).

Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.

In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?

Input

The first line contains two integers n and k (2≤ n≤ 2 ⋅ 10^5, 1≤ k< n) — the number of cities and industry cities respectively.

Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is a road connecting city u and city v.

It is guaranteed that from any city, you can reach any other city by the roads.

Output

Print the only line containing a single integer — the maximum possible sum of happinesses of all envoys.

Examples

Input

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

Output

7

Input

4 1
1 2
1 3
2 4

Output

2

Input

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

Output

9

Note

<image>

In the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.

<image>

In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2.

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

n,k = map(int,input().split())
graph = [set([]) for _ in range(n+1)]

for _ in range(n-1):
    x,y = map(int,input().split())
    graph[x].add(y)
    graph[y].add(x)

dep,par,cn = [0]*(n+1),[0]*(n+1),0
q,p = [1],[]
vis = [0]*(n+1)
vis[1] = 1

while(q):
    x = q.pop()
    dep[x] = cn
    for i in graph[x]:
        if(vis[i] == 0):
            vis[i] = 1
            p.append(i)
            par[i] = x
    if(len(q) == 0):
        cn += 1
        q = list(p)
        p = []

tp = []
for i in range(1,n+1):
    tp.append((i,dep[i]))
tp.sort(key = lambda x : (x[1]))
tp = tp[::-1]

sub = [0]*(n+1)
for i in range(len(tp)-1):
    ind = tp[i][0]
    pid = par[ind]
    sub[pid] += 1 + sub[ind]

a = []
for i in range(1,n+1):
    a.append(dep[i]-sub[i])
a.sort(reverse = True)

sn = 0
for i in range(k):
    sn += a[i]

stdout.write(str(sn)+'\n')
```


135_A. Replacement

Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all.

After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.

Input

The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.

Output

Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.

Examples

Input

5
1 2 3 4 5

Output

1 1 2 3 4

Input

5
2 3 4 5 6

Output

1 2 3 4 5

Input

3
2 2 2

Output

1 2 2

```python
n = int(input())
a = sorted(map(int, input().split()))

ans = [0]*n
ans[0] = 1
f = ans[0] != a[0]
for i in range(1, n):
    ans[i] = a[i-1]
    if ans[i] != a[i]:
        f = True

m = 10**9
if not f:
    for i in range(n-1, -1, -1):
        if ans[i] < m:
            ans[i] += 1
            break

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


137_B. Permutation

"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.

The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.

You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

Input

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Output

Print the only number — the minimum number of changes needed to get the permutation.

Examples

Input

3
3 1 2

Output

0

Input

2
2 2

Output

1

Input

5
5 3 3 3 1

Output

2

Note

The first sample contains the permutation, which is why no replacements are required.

In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.

In the third sample we can replace the second element with number 4 and the fourth element with number 2.

```python
n = int(input())
l = list(map(int,input().split()))
cnt=0
for i in range(1,n+1):
    if i not in l:
        cnt+=1
print(cnt)
```


13_B. Letter A

Little Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.

You are given three segments on the plane. They form the letter A if the following conditions hold:

  * Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments.
  * The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.
  * The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4).

Input

The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.

Output

Output one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.

Examples

Input

3
4 4 6 0
4 1 5 2
4 0 4 4
0 0 0 6
0 6 2 -4
1 1 0 1
0 0 0 5
0 5 2 -1
1 2 0 1

Output

YES
NO
YES

```python
__author__ = 'Darren'

def solve():
    t = int(input())
    while t:
        run()
        t -= 1

def run():
    def check_condition_1():
        record = {}
        common, first, second = None, -1, -1
        found = False
        for i in range(3):
            for j in range(2):
                if segments[i][j] in record:
                    if found:
                        return False
                    found = True
                    common = segments[i][j]
                    first, second = record[segments[i][j]], i
                else:
                    record[segments[i][j]] = i
        if not found:
            return False

        segments[0], segments[first] = segments[first], segments[0]
        segments[1], segments[second] = segments[second], segments[1]
        if common != segments[0][0]:
            segments[0][0], segments[0][1] = segments[0][1], segments[0][0]
        if common != segments[1][0]:
            segments[1][0], segments[1][1] = segments[1][1], segments[1][0]

        nonlocal vector1, vector2, vector3, vector4
        vector1 = Vector2D(segments[0][0], segments[0][1])
        vector2 = Vector2D(segments[1][0], segments[1][1])
        vector3 = Vector2D(segments[0][0], segments[2][0])
        vector4 = Vector2D(segments[1][0], segments[2][1])
        if vector1.parallel(vector3):
            return vector2.parallel(vector4)
        else:
            vector3 = Vector2D(segments[0][0], segments[2][1])
            vector4 = Vector2D(segments[1][0], segments[2][0])
            return vector1.parallel(vector3) and vector2.parallel(vector4)

    def check_condition_2():
        return vector1.acute_or_perpendicular(vector2)

    def check_condition_3():
        return (0.2 <= vector1.dot_product(vector3) / vector1.distance_square() <= 0.8 and
                0.2 <= vector2.dot_product(vector4) / vector2.distance_square() <= 0.8)

    segments = []
    for _i in range(3):
        temp = [int(x) for x in input().split()]
        segments.append([(temp[0], temp[1]), (temp[2], temp[3])])
    vector1, vector2, vector3, vector4 = None, None, None, None
    if check_condition_1() and check_condition_2() and check_condition_3():
        print('YES')
    else:
        print('NO')

class Vector2D:
    def __init__(self, p1, p2):
        self.x = p2[0] - p1[0]
        self.y = p2[1] - p1[1]

    def distance_square(self):
        return self.x ** 2 + self.y ** 2

    def __sub__(self, other):
        return Vector2D(self.x - other.x, self.y - other.y)

    def dot_product(self, other):
        return self.x * other.x + self.y * other.y

    def cross_product(self, other):
        return self.x * other.y - self.y * other.x

    def parallel(self, other):
        return self.cross_product(other) == 0

    def acute_or_perpendicular(self, other):
        return self.dot_product(other) >= 0 and not self.parallel(other)

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


1423_K. Lonely Numbers

In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.

More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.

Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.

In a group of numbers, a number is lonely if it doesn't have any friends in that group.

Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?

Input

The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.

On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.

Output

For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.

Example

Input

3
1 5 10

Output

1
3
3

Note

For first test case, 1 is the only number and therefore lonely.

For second test case where n=5, numbers 1, 3 and 5 are lonely.

For third test case where n=10, numbers 1, 5 and 7 are lonely.

```python
# This code is contributed by Siddharth

import os, io

input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# setrecursionlimit(10**6)
# from sys import *

import random
from bisect import *
import math
from collections import *
import operator
from heapq import *
from itertools import *
inf=10**18
mod=10**9+7

# inverse modulo power pow(a,-1,mod) - it only works on py 3.8 ( *not in pypy )

# ==========================================> Code Starts Here <=====================================================================
def findprime():
    n = 1000000
    prime = [1 for i in range(n + 1)]
    prime[0] = 0
    prime[1] = 0
    p = 2
    while p * p <= n:
        if prime[p]:
            for i in range(p * p, n + 1, p):
                prime[i] = 0
        p += 1
    for i in range(1, n + 1):
        prime[i] += prime[i - 1]
    return prime

n=int(input())
a=list(map(int,input().split()))
prime=findprime()
for i in a:
    temp=int(math.sqrt(i))
    print(prime[i]-prime[temp]+1)

```


1443_D. Extreme Subtraction

You are given an array a of n positive integers.

You can use the following operation as many times as you like: select any integer 1 ≤ k ≤ n and do one of two things:

  * decrement by one k of the first elements of the array.
  * decrement by one k of the last elements of the array.

For example, if n=5 and a=[3,2,2,1,4], then you can apply one of the following operations to it (not all possible options are listed below):

  * decrement from the first two elements of the array. After this operation a=[2, 1, 2, 1, 4];
  * decrement from the last three elements of the array. After this operation a=[3, 2, 1, 0, 3];
  * decrement from the first five elements of the array. After this operation a=[2, 1, 1, 0, 3];

Determine if it is possible to make all the elements of the array equal to zero by applying a certain number of operations.

Input

The first line contains one positive integer t (1 ≤ t ≤ 30000) — the number of test cases. Then t test cases follow.

Each test case begins with a line containing one integer n (1 ≤ n ≤ 30000) — the number of elements in the array.

The second line of each test case contains n integers a_1 … a_n (1 ≤ a_i ≤ 10^6).

The sum of n over all test cases does not exceed 30000.

Output

For each test case, output on a separate line:

  * YES, if it is possible to make all elements of the array equal to zero by applying a certain number of operations.
  * NO, otherwise.

The letters in the words YES and NO can be outputed in any case.

Example

Input

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

Output

YES
YES
NO
YES

```python
#not done by myself
t=int(input())
fflg=0
if t==3000: fflg=1
cnt=1
while t!=0:

    t-=1
    n=int(input())
    lst=input().split(" ")
   # if fflg==1 and cnt==59: print(lst)
    for i in range(0,n,1):
        lst[i]=int(lst[i])
    flg=0
    mini=1000000000000000
    psum=[0 for i in range(0,n+1,1)]

    for i in range(0,n-1,1):
        mini=min(mini,lst[i])
        if(lst[i+1]<lst[i]):
            x=lst[i]-lst[i+1]
            psum[0]-=x
            psum[i+1]+=x

    cnt+=1
    for i in range(1,n+1,1):
        psum[i]+=psum[i-1]
    for i in range(0,n,1):
        if lst[i] + psum[i] <0: flg=1

    if(flg==1): print("NO")
    else: print("YES")
```


1468_M. Similar Sets

You are given n sets of integers. The i-th set contains k_i integers.

Two sets are called similar if they share at least two common elements, i. e. there exist two integers x and y such that x ≠ y, and they both belong to each of the two sets.

Your task is to find two similar sets among the given ones, or report that there is no such pair of sets.

Input

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

The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5) the number of given sets. The following n lines describe the sets. The i-th line starts with an integer k_i (2 ≤ k_i ≤ 10^5) — the number of integers in the i-th set. Then k_i integers a_{i,1}, a_{i,2}, ..., a_{i,k_i} (1 ≤ a_{i,j} ≤ 10^9) follow — the elements of the i-th set. It is guaranteed that all elements in each set are different.

The total number of elements in all sets in all test cases is not greater than 2⋅ 10^5.

Output

For each test case, print the answer on a single line.

If there is no pair of similar sets, print -1.

Otherwise, print two different integers — the indices of the similar sets. The sets are numbered from 1 to n in the order they are given in the input. If there are multiple answers, print any of them.

Example

Input

3
4
2 1 10
3 1 3 5
5 5 4 3 2 1
3 10 20 30
3
4 1 2 3 4
4 2 3 4 5
4 3 4 5 6
2
3 1 3 5
3 4 3 2

Output

2 3
1 2
-1

```python
def solve(n, debug=False):
    global curr;    global seen;    global last;    big = [];    small = []
    for i in range(1,1+n):
        l = list(map(int, input().split()))
        if l[0] > 600:            big.append((i,l[1:]))
        else:            small.append((i,l[1:]))
    s1 = len(big);    s2 = len(small)
    if debug:  print(s1,s2);   return ''
    for s, l1 in big:
        care = set(l1)
        for t, l2 in big + small:
            if s == t: continue
            count = 0
            for v in l2:
                if v in care:  count += 1
            if count >= 2:   return str(s) + ' ' + str(t)
    mapD = dict();   curr = 0; seen = [];   last = [] ;msmall = []
    def mapV(x):
        global curr;    global seen;    global last
        if x in mapD:    return mapD[x]
        else:  mapD[x] = curr;  curr += 1;  seen.append([]);  last.append((-1,-1)); return curr - 1
    for i in range(s2):
        u, l = small[i];   new = []
        for v in l:  seen[mapV(v)].append(i);   new.append(mapV(v))
        msmall.append(new)
    for v1 in range(len(seen)):
        for i in seen[v1]:
            for v2 in msmall[i]:
                if v1 == v2: continue
                lastV = last[v2]
                if lastV[0] == v1:   return str(lastV[1]) + ' ' + str(small[i][0])
                else:     last[v2] = (v1, small[i][0])
    return '-1'
import sys,io,os;input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
t = int(input())
o = []
for _ in range(t):
    n = int(input())

    if n > 80000:
        o.append(solve(n))
        continue

    seen = dict()
    out = (-1,-1)

    for s in range(n):
        adj = set()
        adjL = set()
        l = list(map(int, input().split()))
        for v in l[1:]:
            if v in seen:
                ot = seen[v]
                if len(ot) > len(adjL) and len(ot) > len(adj):
                    adj |= adjL
                    adjL = ot
                    for u in adj:
                        if u in adjL:
                            out = (u, s)
                            break
                else:
                    for u in ot:
                        if u in adj or u in adjL:
                            out = (u, s)
                            break
                        else:
                            adj.add(u)

                if out[0] == -1:
                    seen[v].add(s)
                else:
                    break
            else:
                seen[v] = set([s])

        if out[0] != -1:
            while s < n-1:
                input()
                s += 1
            break
    o.append( ('-1' if out[0] == -1 else str(out[0] + 1) + ' ' + str(out[1] + 1) ))
print('\n'.join(o))
```


1494_A. ABC String

You are given a string a, consisting of n characters, n is even. For each i from 1 to n a_i is one of 'A', 'B' or 'C'.

A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.

You want to find a string b that consists of n characters such that:

  * b is a regular bracket sequence;
  * if for some i and j (1 ≤ i, j ≤ n) a_i=a_j, then b_i=b_j.

In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.

Your task is to determine if such a string b exists.

Input

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

Then the descriptions of t testcases follow.

The only line of each testcase contains a string a. a consists only of uppercase letters 'A', 'B' and 'C'. Let n be the length of a. It is guaranteed that n is even and 2 ≤ n ≤ 50.

Output

For each testcase print "YES" if there exists such a string b that:

  * b is a regular bracket sequence;
  * if for some i and j (1 ≤ i, j ≤ n) a_i=a_j, then b_i=b_j.

Otherwise, print "NO".

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

Example

Input

4
AABBAC
CACA
BBBBAC
ABCA

Output

YES
YES
NO
NO

Note

In the first testcase one of the possible strings b is "(())()".

In the second testcase one of the possible strings b is "()()".

```python
from typing import Callable, Iterator, TypeVar, cast

_F = TypeVar("_F", bound=Callable[[], None])

def repeater(func: _F) -> _F:
    def wrapper():
        for _ in range(int(input())):
            func()

    return cast(_F, wrapper)

def get_num_input() -> Iterator[int]:
    return map(int, input().split())

@repeater
def main() -> None:
    # input()

    group: str = "ABC"
    pair: str = "()"

    string: str = input()

    index: int
    for index in [0, -1]:
        group = group.replace(string[index], "")
        string = string.replace(string[index], pair[index])

    string = string.replace(group, pair[string.count("(") > string.count(")")])

    while string.count("(") == string.count(")") and pair in string:
        string = string.replace(pair, "")

    print("NO" if string else "YES")

if __name__ == "__main__":
    main()

```


1516_D. Cut

This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array a of length n written on it, and then he does the following:

  * he picks a range (l, r) and cuts the subsegment a_l, a_{l + 1}, …, a_r out, removing the rest of the array.
  * he then cuts this range into multiple subranges.
  * to add a number theory spice to it, he requires that the elements of every subrange must have their product equal to their [least common multiple (LCM)](https://en.wikipedia.org/wiki/Least_common_multiple).

Formally, he partitions the elements of a_l, a_{l + 1}, …, a_r into contiguous subarrays such that the product of every subarray is equal to its LCM. Now, for q independent ranges (l, r), tell Baby Ehab the minimum number of subarrays he needs.

Input

The first line contains 2 integers n and q (1 ≤ n,q ≤ 10^5) — the length of the array a and the number of queries.

The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^5) — the elements of the array a.

Each of the next q lines contains 2 integers l and r (1 ≤ l ≤ r ≤ n) — the endpoints of this query's interval.

Output

For each query, print its answer on a new line.

Example

Input

6 3
2 3 10 7 5 14
1 6
2 4
3 5

Output

3
1
2

Note

The first query asks about the whole array. You can partition it into [2], [3,10,7], and [5,14]. The first subrange has product and LCM equal to 2. The second has product and LCM equal to 210. And the third has product and LCM equal to 70. Another possible partitioning is [2,3], [10,7], and [5,14].

The second query asks about the range (2,4). Its product is equal to its LCM, so you don't need to partition it further.

The last query asks about the range (3,5). You can partition it into [10,7] and [5].

```python
mod = 1000000007
eps = 10**-9

def main():
    import sys
    from math import gcd
    input = sys.stdin.buffer.readline

    V = 10**5
    minfactor = list(range(V+1))
    for d in range(2, V+1):
        for x in range(2, V+1):
            if d*x > V:
                break
            if minfactor[d*x] == d*x:
                minfactor[d*x] = d

    N, Q = map(int, input().split())
    A = [0] + list(map(int, input().split())) + [1]
    N += 1

    M = 1
    seen = [0] * (V+1)
    r = 1
    nxt_0 = [-1] * (N+1)
    for l in range(1, N+1):
        while True:
            if r == N:
                break
            a = A[r]
            d_set = set()
            while a != 1:
                d = minfactor[a]
                d_set.add(d)
                a //= d
            ok = 1
            for d in d_set:
                if seen[d]:
                    ok = 0
                    break
            if not ok:
                break
            else:
                r += 1
                for d in d_set:
                    seen[d] = 1
        nxt_0[l] = r
        a = A[l]
        while a != 1:
            d = minfactor[a]
            seen[d] = 0
            a //= d
    nxt = [[-1] * (N+1) for _ in range(18)]
    nxt[0] = nxt_0
    for lv in range(1, 18):
        for l in range(1, N+1):
            nxt[lv][l] = nxt[lv-1][nxt[lv-1][l]]

    for _ in range(Q):
        l, r = map(int, input().split())
        ans = 0
        for lv in range(17, -1, -1):
            l_new = nxt[lv][l]
            if l_new <= r:
                ans += 1 << lv
                l = l_new
        ans += 1
        print(ans)

if __name__ == '__main__':
    main()

```


171_F. ucyhf

qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.

Input

jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 ≤ d ≤ 11184) — jxu edu-rqiut ydtun ev jxu ucyhf je vydt.

Output

ekjfkj q iydwbu dkcruh.

Examples

Input

1

Output

13

```python
#!/usr/bin/env python
from __future__ import division, print_function
import math
import os
import sys
from fractions import *
from sys import *
from io import BytesIO, IOBase
from itertools import *
from collections import *
# sys.setrecursionlimit(10**5)

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
# sys.setrecursionlimit(10**6)

# region fastio

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")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

def inp(): return sys.stdin.readline().rstrip("\r\n")  # for fast input

def out(var): sys.stdout.write(str(var))  # for fast output, always take string

def lis(): return list(map(int, inp().split()))

def stringlis(): return list(map(str, inp().split()))

def sep(): return map(int, inp().split())

def strsep(): return map(str, inp().split())

def fsep(): return map(float, inp().split())

def inpu(): return int(inp())
# -----------------------------------------------------------------

def regularbracket(t):
    p = 0
    for i in t:
        if i == "(":
            p += 1
        else:
            p -= 1
        if p < 0:
            return False
    else:
        if p > 0:
            return False
        else:
            return True

# -------------------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left) / 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid] <= key):
            count = mid + 1
            left = mid + 1
         # If key is smaller, ignore right half
        else:
            right = mid - 1
    return count

# ------------------------------reverse string(pallindrome)
def reverse1(string):
    pp = ""
    for i in string[::-1]:
        pp += i
    if pp == string:
        return True
    return False

# --------------------------------reverse list(paindrome)
def reverse2(list1):
    l = []
    for i in list1[::-1]:
        l.append(i)
    if l == list1:
        return True
    return False

def mex(list1):
    # list1 = sorted(list1)
    p = max(list1) + 1
    for i in range(len(list1)):
        if list1[i] != i:
            p = i
            break
    return p

def sumofdigits(n):
    n = str(n)
    s1 = 0
    for i in n:
        s1 += int(i)
    return s1

def perfect_square(n):
    s = math.sqrt(n)
    if s == int(s):
        return True
    return False

# -----------------------------roman
def roman_number(x):
    if x > 15999:
        return
    value = [5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    symbol = ["F", "MF", "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
    roman = ""
    i = 0
    while x > 0:
        div = x // value[i]
        x = x % value[i]
        while div:
            roman += symbol[i]
            div -= 1
        i += 1
    return roman

def soretd(s):
    for i in range(1, len(s)):
        if s[i - 1] > s[i]:
            return False
    return True

# print(soretd("1"))
# ---------------------------
def countRhombi(h, w):
    ct = 0
    for i in range(2, h + 1, 2):
        for j in range(2, w + 1, 2):
            ct += (h - i + 1) * (w - j + 1)
    return ct

def countrhombi2(h, w):
    return ((h * h) // 4) * ((w * w) // 4)

# ---------------------------------
def binpow(a, b):
    if b == 0:
        return 1
    else:
        res = binpow(a, b // 2)
    if b % 2 != 0:
        return res * res * a
    else:
        return res * res

# -------------------------------------------------------
def binpowmodulus(a, b, m):
    a %= m
    res = 1
    while (b > 0):
        if (b & 1):
            res = res * a % m
        a = a * a % m
        b >>= 1
    return res

# -------------------------------------------------------------
def coprime_to_n(n):
    result = n
    i = 2
    while (i * i <= n):
        if (n % i == 0):
            while (n % i == 0):
                n //= i
            result -= result // i
        i += 1
    if (n > 1):
        result -= result // n
    return result

# -------------------prime
def prime(x):
    if x == 1:
        return False
    else:
        for i in range(2, int(math.sqrt(x)) + 1):
            if (x % i == 0):
                return False
        else:
            return True

def luckynumwithequalnumberoffourandseven(x, n, a):
    if x >= n and str(x).count("4") == str(x).count("7"):
        a.append(x)
    else:
        if x < 1e12:
            luckynumwithequalnumberoffourandseven(x * 10 + 4, n, a)
            luckynumwithequalnumberoffourandseven(x * 10 + 7, n, a)
    return a

def luckynuber(x, n, a):
    p = set(str(x))
    if len(p) <= 2:
        a.append(x)
    if x < n:
        luckynuber(x + 1, n, a)
    return a
#------------------------------------------------------interactive problems

def interact(type, x):
    if type == "r":
        inp = input()
        return inp.strip()
    else:
        print(x, flush=True)

#------------------------------------------------------------------zero at end of factorial of a number
def findTrailingZeros(n):
    # Initialize result
    count = 0

    # Keep dividing n by
    # 5 & update Count
    while (n >= 5):
        n //= 5
        count += n

    return count
#-----------------------------------------------merge sort
# Python program for implementation of MergeSort
def mergeSort(arr):
    if len(arr) > 1:

        # Finding the mid of the array
        mid = len(arr) // 2

        # Dividing the array elements
        L = arr[:mid]

        # into 2 halves
        R = arr[mid:]

        # Sorting the first half
        mergeSort(L)

        # Sorting the second half
        mergeSort(R)

        i = j = k = 0

        # Copy data to temp arrays L[] and R[]
        while i < len(L) and j < len(R):
            if L[i] < R[j]:
                arr[k] = L[i]
                i += 1
            else:
                arr[k] = R[j]
                j += 1
            k += 1

        # Checking if any element was left
        while i < len(L):
            arr[k] = L[i]
            i += 1
            k += 1

        while j < len(R):
            arr[k] = R[j]
            j += 1
            k += 1
#-----------------------------------------------lucky number with two lucky any digits
res = set()
def solve(p, l, a, b,n):#given number
    if p > n or l > 10:
        return
    if p > 0:
        res.add(p)
    solve(p * 10 + a, l + 1, a, b,n)
    solve(p * 10 + b, l + 1, a, b,n)
# problem
"""
n = int(input())
for a in range(0, 10):
    for b in range(0, a):
        solve(0, 0)
print(len(res))
"""
#-----------------------------------------------
# endregion------------------------------
"""
def main():
    n = inpu()
    cnt=0

    c = n
    if n % 7 == 0:
            print("7" * (n // 7))
    else:
        while(c>0):
            c-=4
            cnt+=1
            if c%7==0 and c>=0:
                #print(n,n%4)
                print("4"*(cnt)+"7"*(c//7))
                break
        else:
            if n % 4 == 0:
                print("4" * (n // 4))
            else:
                print(-1)
if __name__ == '__main__':
    main()
"""
"""
def main():
    n,t = sep()
    arr = lis()
    i=0
    cnt=0
    min1 = min(arr)
    while(True):
        if t>=arr[i]:
            cnt+=1
            t-=arr[i]
            i+=1
        else:
            i+=1
        if i==n:
            i=0
        if t<min1:
            break
    print(cnt)
if __name__ == '__main__':
    main()
"""

# Python3 program to find all subsets
# by backtracking.

# In the array A at every step we have two
# choices for each element either we can
# ignore the element or we can include the
# element in our subset
def subsetsUtil(A, subset, index,d):
    print(*subset)
    s = sum(subset)
    d.append(s)
    for i in range(index, len(A)):
        # include the A[i] in subset.
        subset.append(A[i])

        # move onto the next element.
        subsetsUtil(A, subset, i + 1,d)

        # exclude the A[i] from subset and
        # triggers backtracking.
        subset.pop(-1)
    return d
def subsetSums(arr, l, r,d, sum=0):
    if l > r:
        d.append(sum)
        return
    subsetSums(arr, l + 1, r,d, sum + arr[l])

    # Subset excluding arr[l]
    subsetSums(arr, l + 1, r,d, sum)
    return d
"""
def main():
    t = inpu()
    for _ in range(t):
        n = inpu()
        arr=[]
        subset=[]
        i=0
        l=[]
        for j in range(26):
            arr.append(3**j)

if __name__ == '__main__':
    main()
"""
"""
def main():
    n = int(input())
    cnt=1
    if n==1:
        print(1)
    else:
        for i in range(1,n):
            cnt+=i*12
        print(cnt)
if __name__ == '__main__':
    main()
"""

def f(n):
    i = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += 1
    return True

n = int(input())
for i in range(10, 1000000):
    if i != int(str(i)[::-1]) and f(i) and f(int(str(i)[::-1])):
        n -= 1
    if n == 0:
        print(i)
        break

```


215_D. Hot Days

The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 ≤ i ≤ n) region has a stable temperature of ti degrees in summer.

This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is ti + k degrees.

Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.

To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.

Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.

Input

The first input line contains two integers n and m (1 ≤ n ≤ 105; 1 ≤ m ≤ 106) — the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1 ≤ ti, Ti, xi, costi ≤ 106). The numbers in the lines are separated by single spaces.

Output

Print the only integer — the minimum number of roubles the organizers will have to spend to transport all schoolchildren.

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

Examples

Input

2 10
30 35 1 100
20 35 10 10

Output

120

Input

3 100
10 30 1000 1
5 10 1000 3
10 40 1000 100000

Output

200065

Note

In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles.

```python
import sys

n, m = map(int, sys.stdin.readline().split())

ans = 0

for _ in range(n):
    ti, Ti, xi, ci = map(int, sys.stdin.readline().split())
    cost = xi * m * (ti + m > Ti) + ci
    if ti < Ti:
        cost2 = ci * ((m - 1) // (Ti - ti) + 1)
        cost = min(cost, cost2)

    ans += cost

print(ans)

```


264_B. Good Sequences

Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.

Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:

  * The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1).
  * No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).
  * All elements of the sequence are good integers.

Find the length of the longest good sequence.

Input

The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).

Output

Print a single integer — the length of the longest good sequence.

Examples

Input

5
2 3 4 6 9

Output

4

Input

9
1 2 3 5 6 7 8 9 10

Output

4

Note

In the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4.

```python
 ######      ###      #######    #######    ##      #     #####        ###     #####
 #     #    #   #          #        #       # #     #    #     #      #   #     ###
 #     #   #     #        #         #       #  #    #   #       #    #     #    ###
 ######   #########      #          #       #   #   #   #           #########    #
 ######   #########     #           #       #    #  #   #           #########    #
 #     #  #       #    #            #       #     # #   #    ####   #       #    #
 #     #  #       #   #             #       #      ##   #    #  #   #       #
 ######   #       #  #######     #######    #       #    #####  #   #       #    #

# from __future__ import print_function # for PyPy2
from collections import Counter, OrderedDict
from itertools import permutations as perm
from fractions import Fraction
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
from math import *

g   = lambda : stdin.readline().strip()
gl  = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")

n, = gil()
a = gil()

def getPrimes(x):
	p = []

	if x&1 == 0:
		p.append(2)

	while x&1 == 0:
		x //= 2

	for i in range(3, ceil(sqrt(x))+1):
		if x%i == 0:
			p.append(i)

		while x%i == 0:
			x //= i

	if x > 1:
		p.append(x)

	return p

primes = {}
ans = 1

for v in a:
	maxP = 0
	local_primes = getPrimes(v)
	# print(local_primes, primes)
	for p in local_primes:
		maxP = max(maxP, primes.get(p, 0))

	for p in local_primes:
		primes[p] = maxP+1

	ans = max(maxP+1, ans)

print(ans)

```


288_B. Polo the Penguin and Houses

Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n).

Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.

We know that:

  1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
  2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
  3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.

You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).

Input

The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the number k from the statement.

Output

In a single line print a single integer — the answer to the problem modulo 1000000007 (109 + 7).

Examples

Input

5 2

Output

54

Input

7 4

Output

1728

```python
import sys,math,heapq,copy
from collections import defaultdict,deque
from bisect import bisect_left,bisect_right
from functools import cmp_to_key
from itertools import permutations,combinations,combinations_with_replacement
# sys.setrecursionlimit(10**6)
# sys.stdin=open('Input.txt','r')
# sys.stdout=open('Output.txt','w')
mod=1000000007
# Reading Single Input
def get_int(): return int(sys.stdin.readline().strip())
def get_str(): return sys.stdin.readline().strip()
def get_float(): return float(sys.stdin.readline().strip())
# Reading Multiple Inputs
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_strs(): return map(str, sys.stdin.readline().strip().split())
def get_floats(): return map(float, sys.stdin.readline().strip().split())
# Reading List Of Inputs
def list_ints(): return list(map(int, sys.stdin.readline().strip().split()))
def list_strs(): return list(map(str, sys.stdin.readline().strip().split()))
def list_floats(): return list(map(float, sys.stdin.readline().strip().split()))
# ------------------------------------------------------------------------------------- #

n,k=get_ints()
print((pow(k,k-1,mod)*pow(n-k,n-k,mod))%mod)
```


313_B. Ilya and Queries

Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.

You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n). The answer to the query li, ri is the number of such integers i (li ≤ i < ri), that si = si + 1.

Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.

Input

The first line contains string s of length n (2 ≤ n ≤ 105). It is guaranteed that the given string only consists of characters "." and "#".

The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≤ li < ri ≤ n).

Output

Print m integers — the answers to the queries in the order in which they are given in the input.

Examples

Input

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

Output

1
1
5
4

Input

#..###
5
1 3
5 6
1 5
3 6
3 4

Output

1
1
2
2
0

```python

s=input()
n=len(s)
m=int(input())

a=[0]*(n+1)
for i in range(n-1):
	a[i+1]=a[i]+(s[i]==s[i+1])
ans=""
for i in range(m):
	l,r=map(int,input().split())
	ans+=str(a[r-1]-a[l-1])+" "
print(*ans.split(),sep="\n")

```


402_C. Searching for Graph

Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:

  * the graph contains exactly 2n + p edges;
  * the graph doesn't contain self-loops and multiple edges;
  * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges.

A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.

Your task is to find a p-interesting graph consisting of n vertices.

Input

The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test.

It is guaranteed that the required graph exists.

Output

For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.

Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.

Examples

Input

1
6 0

Output

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

```python
for _ in range(int(input())):
    n, p = map(int, input().split())
    p += 2 * n
    for i in range(n):
        for j in range(i + 1, n):
            if p == 0:
                break
            print(i + 1, j + 1)
            p -= 1

```


42_D. Strange town

Volodya has recently visited a very odd town. There are N tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour — a cycle which visits every attraction exactly once — the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.

Input

Input contains just one natural number (3 ≤ N ≤ 20) — the number of town attractions.

Output

Output should contain N rows containing N positive integer numbers each — the adjacency matrix of the prices graph (thus, j-th number in i-th row should be equal to the price of the road between the j-th and the i-th attraction). Diagonal numbers should be equal to zero. All numbers should not be greater than 1000. All prices should be positive and pairwise distinct. If there are several solutions, output any of them.

Examples

Input

3

Output

0 3 4
3 0 5
4 5 0

```python
#codeforces 42d: strange town: math, constructive algorithm

def readGen(trans):
	while 1:
		for x in input().split():
			yield(trans(x))
readint=readGen(int)

n=next(readint)

def constructRow(n):
	can=[1 for i in range(1001)]
	b=[0 for i in range(n+1)]
	b[2]=1
	b[3]=2
	can[1]=0
	can[2]=0
	for k in range(4,n+1):
		b[k]=b[k-1]+1
		while (not can[b[k]]): b[k]+=1
		can[b[k]]=0
		for i in range(2,k):
			for p in range(2,k):
				can[b[k]+b[p]-b[i]]=0
	return b

def constructMatrix(b,n):
	can=[1 for i in range(1001)]
	for i in range(2,n+1):
		for j in range(2,n+1):
			for p in range(2,n+1):
				can[b[2]+b[3]+b[p]-b[i]-b[j]]=0
	x=1
	while (not can[x]): x+=1
	a=[[0 for j in range(n+1)] for i in range(n+1)]
	for i in range(n+1):
		a[1][i]=a[i][1]=b[i]
	for i in range(2,n+1):
		for j in range(i+1,n+1):
			a[i][j]=a[j][i]=b[i]+b[j]+x-b[2]-b[3]
	return a

b=constructRow(n)
#print(b)

a=constructMatrix(b,n)
for i in range(1,n+1):
	for j in range(1,n+1):
		print("{:4}".format(a[i][j]),end='')
	print()

```


452_B. 4-point polyline

You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.

A polyline defined by points p1, p2, p3, p4 consists of the line segments p1 p2, p2 p3, p3 p4, and its length is the sum of the lengths of the individual line segments.

Input

The only line of the input contains two integers n and m (0 ≤ n, m ≤ 1000). It is guaranteed that grid contains at least 4 different points.

Output

Print 4 lines with two integers per line separated by space — coordinates of points p1, p2, p3, p4 in order which represent the longest possible polyline.

Judge program compares your answer and jury's answer with 10 - 6 precision.

Examples

Input

1 1

Output

1 1
0 0
1 0
0 1

Input

0 10

Output

0 1
0 10
0 0
0 9


474_F. Ant colony

Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.

In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).

After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.

In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.

Input

The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.

The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.

The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.

Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.

Output

Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].

Examples

Input

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

Output

4
4
1
1

Note

In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.

In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.

In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.

In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.

```python
from math import gcd

class SegTree:
    def __init__(self, arr = None, length = None):
        """
        Creates a segment tree. If arr (a list) is given, length is ignored,
        and we build a segment tree with underlying array arr. If no list is
        given, length (an int) must be given, and we build a segment tree with
        underlying all-zero array of that length.
        """
        if arr is not None:
            self.n = len(arr)
            self.t = [1 for _ in range(2*self.n)]
            self.ct = [0]*self.n + [1]*self.n
            self.construct(arr)
        else:
            assert False
            self.n = length
            self.t = [1 for _ in range(2*self.n)]

    def construct(self, arr):
        """
        Constructs the segment tree from given array (assumed to be of the
        right length).
        """
        self.t[self.n:] = arr
        for i in reversed(range(0, self.n)):
            self.t[i] = gcd(self.t[i*2], self.t[i*2+1])
            # print(i, self.t[i], self.t[i*2], self.t[i*2+1])
            if self.t[i] == self.t[i*2]:
                self.ct[i] += self.ct[i*2]
            if self.t[i] == self.t[i*2 + 1]:
                self.ct[i] += self.ct[i*2 + 1]

    def modify(self, p, val):
        """
        Sets the value at index p to val.
        """
        p += self.n
        self.t[p] = val
        self.ct[p] = 1
        while p > 1:
            self.t[p//2] = gcd(self.t[p], self.t[p ^ 1])
            self.ct[p//2] = 0
            if self.t[p//2] == self.t[p]:
                self.ct[p//2] += self.ct[p]
            if self.t[p//2] == self.t[p ^ 1]:
                self.ct[p//2] += self.ct[p ^ 1]
            p //= 2

    def gcd_query(self, l, r):
        l += self.n
        r += self.n
        res = self.t[l]
        while l < r:
            if l&1:
                res = gcd(res, self.t[l])
                l += 1
            if r&1:
                r -= 1
                res = gcd(res, self.t[r])
            l //= 2
            r //= 2
        return res

    def query_num_eq_gcd(self, l, r):
        """
        Gets the sum of all values in the range [l, r) in the underlying array.
        """
        my_gcd = self.gcd_query(l, r)
        l += self.n
        r += self.n
        res = 0
        while l < r:
            if l&1:
                if self.t[l] == my_gcd:
                    res += self.ct[l]
                l += 1
            if r&1:
                r -= 1
                if self.t[r] == my_gcd:
                    res += self.ct[r]
            l //= 2
            r //= 2
        return res

import sys
n = int(input())
s = [int(x) for x in input().split()]
st = SegTree(arr=s)
t = int(input())
for _ in range(t):
    l, r = [int(x) for x in sys.stdin.readline().split()]
    # print(f"gcd = {st.gcd_query(l-1, r)}")
    # print(f"num eq to gcd = {st.query_num_eq_gcd(l-1, r)}")
    print(r - l + 1 - st.query_num_eq_gcd(l-1, r))
    # print(st.t)
    # print(st.ct)
    # print()

```


522_A. Reposts

One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.

These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.

Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.

Input

The first line of the input contains integer n (1 ≤ n ≤ 200) — the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.

We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.

Output

Print a single integer — the maximum length of a repost chain.

Examples

Input

5
tourist reposted Polycarp
Petr reposted Tourist
WJMZBMR reposted Petr
sdya reposted wjmzbmr
vepifanov reposted sdya

Output

6

Input

6
Mike reposted Polycarp
Max reposted Polycarp
EveryOne reposted Polycarp
111 reposted Polycarp
VkCup reposted Polycarp
Codeforces reposted Polycarp

Output

2

Input

1
SoMeStRaNgEgUe reposted PoLyCaRp

Output

2

```python
leng = int(input())
names = ["POLYCARP", 1]
others = []
max = 1
for i in range(leng):
	x, y= map(str, input().split(' reposted '))
	others.append(x.upper())
	others.append(y.upper())
for  i in range(0, leng*2, 2):
	if others[i+1] in names:
		num = names[names.index(others[i+1]) + 1] + 1
		names.append(others[i])
		names.append(num)
		if num>max:
			max = num
		continue
print(max)

```


549_C. The Game Of Parity

There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.

The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.

Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.

Input

The first line contains two positive space-separated integers, n and k (1 ≤ k ≤ n ≤ 2·105) — the initial number of cities in Westeros and the number of cities at which the game ends.

The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 106), which represent the population of each city in Westeros.

Output

Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.

Examples

Input

3 1
1 2 1

Output

Stannis

Input

3 1
2 2 1

Output

Daenerys

Input

6 3
5 20 12 7 14 101

Output

Stannis

Note

In the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.

In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins.

```python
n,k=[int(i) for i in input().split()]
l=[int(i) for i in input().split()]
no=0
for i in l:
    no+=i%2
ne=n-no
if n==k:
    if no%2:
       print("Stannis")
    else:
       print("Daenerys")
else:
    if no<=(n-k)//2:
        print("Daenerys")
    else:
        if no%2:
            if (n-k)%2 and ne<=(n-k)//2 and ne%2==0:
                print("Daenerys")
            elif (n-k)%2==0 and (ne>(n-k)//2 or ne%2):
                print("Daenerys")
            else:
                print("Stannis")
        else:
            if (n-k)%2 and ne<=(n-k)//2 and ne%2:
                print("Daenerys")
            elif (n-k)%2==0 and (ne>(n-k)//2 or ne%2==0):
                print("Daenerys")
            else:
                print("Stannis")

```


597_C. Subsequences

For the given sequence with n different elements find the number of increasing subsequences with k + 1 elements. It is guaranteed that the answer is not greater than 8·1018.

Input

First line contain two integer values n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 10) — the length of sequence and the number of elements in increasing subsequences.

Next n lines contains one integer ai (1 ≤ ai ≤ n) each — elements of sequence. All values ai are different.

Output

Print one integer — the answer to the problem.

Examples

Input

5 2
1
2
3
5
4

Output

7

```python
# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase

def update(tree,pos,diff,si):
    pos += si-1
    while pos:
        tree[pos] += diff
        pos >>= 1

def query(tree,l,r,si):
    ans,l,r = 0,l+si-1,r+si-1
    while l < r:
        if l&1:
            ans += tree[l]
            l += 1
        if not r&1:
            ans += tree[r]
            r -= 1
        l,r = l>>1,r>>1
    return ans+(0 if l!=r else tree[l])

def main():
    n,k = map(int,input().split())
    arr = [int(input()) for _ in range(n)]
    si = 1<<(n.bit_length()-(not n&n-1))
    dp = [[0]*n for _ in range(k+1)]
    dp[0] = [1]*n
    for i in range(1,k+1):
        tree = [0]*(si<<1)
        for j in range(n):
            dp[i][j] = query(tree,1,arr[j],si)
            update(tree,arr[j],dp[i-1][j],si)
    print(sum(dp[-1]))

#Fast IO Region
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")

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


618_E. Robot Arm

Roger is a robot. He has an arm that is a series of n segments connected to each other. The endpoints of the i-th segment are initially located at points (i - 1, 0) and (i, 0). The endpoint at (i - 1, 0) is colored red and the endpoint at (i, 0) is colored blue for all segments. Thus, the blue endpoint of the i-th segment is touching the red endpoint of the (i + 1)-th segment for all valid i.

Roger can move his arm in two different ways:

  1. He can choose some segment and some value. This is denoted as choosing the segment number i and picking some positive l. This change happens as follows: the red endpoint of segment number i and segments from 1 to i - 1 are all fixed in place. Imagine a ray from the red endpoint to the blue endpoint. The blue endpoint and segments i + 1 through n are translated l units in the direction of this ray. <image> <image>

In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B gets translated.

  2. He can choose a segment and rotate it. This is denoted as choosing the segment number i, and an angle a. The red endpoint of the i-th segment will stay fixed in place. The blue endpoint of that segment and segments i + 1 to n will rotate clockwise by an angle of a degrees around the red endpoint. <image> <image>

In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B get rotated around point A.

Roger will move his arm m times. These transformations are a bit complicated, and Roger easily loses track of where the blue endpoint of the last segment is. Help him compute the coordinates of the blue endpoint of the last segment after applying each operation. Note that these operations are cumulative, and Roger's arm may intersect itself arbitrarily during the moves.

Input

The first line of the input will contain two integers n and m (1 ≤ n, m ≤ 300 000) — the number of segments and the number of operations to perform.

Each of the next m lines contains three integers xi, yi and zi describing a move. If xi = 1, this line describes a move of type 1, where yi denotes the segment number and zi denotes the increase in the length. If xi = 2, this describes a move of type 2, where yi denotes the segment number, and zi denotes the angle in degrees. (1 ≤ xi ≤ 2, 1 ≤ yi ≤ n, 1 ≤ zi ≤ 359)

Output

Print m lines. The i-th line should contain two real values, denoting the coordinates of the blue endpoint of the last segment after applying operations 1, ..., i. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.

Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if <image> for all coordinates.

Examples

Input

5 4
1 1 3
2 3 90
2 5 48
1 4 1

Output

8.0000000000 0.0000000000
5.0000000000 -3.0000000000
4.2568551745 -2.6691306064
4.2568551745 -3.6691306064

Note

The following pictures shows the state of the arm after each operation. The coordinates of point F are printed after applying each operation. For simplicity, we only show the blue endpoints of a segment (with the exception for the red endpoint of the first segment). For instance, the point labeled B is the blue endpoint for segment 1 and also the red endpoint for segment 2.

Initial state:

<image> Extend segment 1 by 3.  <image> Rotate segment 3 by 90 degrees clockwise.  <image> Rotate segment 5 by 48 degrees clockwise.  <image> Extend segment 4 by 1.  <image>

```python
from cmath import rect
import sys
import math
from functools import reduce

class SegmentTree():
    def __init__(self, L, function = lambda x,y: x+y):
        self.function = function
        N = self.size = len(L)
        M = 1 << N.bit_length()
        self.margin = 2*M - N
        self.L = [None for i in range(self.margin)] + L
        for i in range(M-1, 0, -1):
            x, y = self.L[i<<1], self.L[i<<1|1]
            self.L[i] = None if x is None or y is None else function(x, y)
    def modify(self, pos, value):
        p = pos + self.margin
        self.L[p] = value
        while p > 1:
            x, y = self.L[p], self.L[p^1]
            if p&1: x, y = y, x
            self.L[p>>1] = None if x is None or y is None else self.function(x, y)
            p>>=1
    def query(self, left, right):
        l, r = left + self.margin, right + self.margin
        stack = []
        void = True
        while l < r:
            if l&1:
                if void:
                    result = self.L[l]
                    void = False
                else:
                    result = self.function(result, self.L[l])
                l+=1
            if r&1:
                r-=1
                stack.append(self.L[r])
            l>>=1
            r>>=1
        init = stack.pop() if void else result
        return reduce(self.function, reversed(stack), init)

def degrect(r, phi):
    return rect(r, math.radians(phi))

def vsum(u, v): #u = (x + y*1j, phi)
    return (u[0] + v[0]*degrect(1, u[1]), (u[1] + v[1])%360)

def solve(f):
    n, m = [int(x) for x in f.readline().split()]
    segments = [[1,0] for i in range(n)]
    arm = SegmentTree([(1,0) for i in range(n)], vsum)
    for line in f:
        q, i, a = [int(x) for x in line.split()]
        if q == 1:
            segments[i-1][0] += a
        else:
            segments[i-1][1] -= a
        arm.modify(i-1, (degrect(segments[i-1][0], segments[i-1][1]), segments[i-1][1]))
        query = arm.query(0,n)[0]
        print(query.real, query.imag)

solve(sys.stdin)

```