1249_B1. Books Exchange (easy version)

The only difference between easy and hard versions is constraints.

There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers from 1 to n (i.e. p is a permutation). The sequence p doesn't change from day to day, it is fixed.

For example, if n=6 and p=[4, 6, 1, 3, 5, 2] then at the end of the first day the book of the 1-st kid will belong to the 4-th kid, the 2-nd kid will belong to the 6-th kid and so on. At the end of the second day the book of the 1-st kid will belong to the 3-th kid, the 2-nd kid will belong to the 2-th kid and so on.

Your task is to determine the number of the day the book of the i-th child is returned back to him for the first time for every i from 1 to n.

Consider the following example: p = [5, 1, 2, 4, 3]. The book of the 1-st kid will be passed to the following kids:

  * after the 1-st day it will belong to the 5-th kid,
  * after the 2-nd day it will belong to the 3-rd kid,
  * after the 3-rd day it will belong to the 2-nd kid,
  * after the 4-th day it will belong to the 1-st kid.

So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.

You have to answer q independent queries.

Input

The first line of the input contains one integer q (1 ≤ q ≤ 200) — the number of queries. Then q queries follow.

The first line of the query contains one integer n (1 ≤ n ≤ 200) — the number of kids in the query. The second line of the query contains n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i are distinct, i.e. p is a permutation), where p_i is the kid which will get the book of the i-th kid.

Output

For each query, print the answer on it: n integers a_1, a_2, ..., a_n, where a_i is the number of the day the book of the i-th child is returned back to him for the first time in this query.

Example

Input

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

Output

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

```python
import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        import os
        self.os = os
        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
        self.BUFSIZE = 8192

    def read(self):
        while True:
            b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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 = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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:
            self.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")

def get_int():
    return int(input())

def get_ints():
    return list(map(int, input().split(' ')))

def get_int_grid(n):
    return [get_ints() for _ in range(n)]

def get_str():
    return input().split(' ')

def yes_no(b):
    if b:
        return "YES"
    else:
        return "NO"

def binary_search(good, left, right, delta=1, right_true=False):
    """
    Performs binary search
    ----------
    Parameters
    ----------
    :param good: Function used to perform the binary search
    :param left: Starting value of left limit
    :param right: Starting value of the right limit
    :param delta: Margin of error, defaults value of 1 for integer binary search
    :param right_true: Boolean, for whether the right limit is the true invariant
    :return: Returns the most extremal value interval [left, right] which is good function evaluates to True,
            alternatively returns False if no such value found
    """

    limits = [left, right]
    while limits[1] - limits[0] > delta:
        if delta == 1:
            mid = sum(limits) // 2
        else:
            mid = sum(limits) / 2
        if good(mid):
            limits[int(right_true)] = mid
        else:
            limits[int(~right_true)] = mid
    if good(limits[int(right_true)]):
        return limits[int(right_true)]
    else:
        return False

def prefix_sums(a, drop_zero=False):
    p = [0]
    for x in a:
        p.append(p[-1] + x)
    if drop_zero:
        return p[1:]
    else:
        return p

def prefix_mins(a, drop_zero=False):
    p = [float('inf')]
    for x in a:
        p.append(min(p[-1], x))
    if drop_zero:
        return p[1:]
    else:
        return p

class DSU:

    # Disjoint Set Union (Union-Find) Data Structure
    def __init__(self, nodes):
        # Parents
        self.p = [i for i in range(nodes)]
        # Ranks
        self.r = [0 for i in range(nodes)]
        # Sizes
        self.s = [1 for i in range(nodes)]

    def get(self, u):
        # Recursive Returns the identifier of the set that contains u, includes path compression
        if u != self.p[u]:
            self.p[u] = self.get(self.p[u])
        return self.p[u]

    def union(self, u, v):
        # Unites the sets with identifiers u and v
        u = self.get(u)
        v = self.get(v)
        if u != v:
            if self.r[u] > self.r[v]:
                u, v = v, u
            self.p[u] = v
            if self.r[u] == self.r[v]:
                self.r[v] += 1
            self.s[v] += self.s[u]

    def get_size(self, u):
        u = self.get(u)
        return self.s[u]

def solve_b():
    n = get_int()
    p = get_ints()
    dsu = DSU(n)
    for i, x in enumerate(p):
        dsu.union(i, x - 1)
    return [dsu.get_size(i) for i in range(n)]

t = get_int()
for _ in range(t):
    print(*solve_b())

```


128_B. String

One day in the IT lesson Anna and Maria learned about the lexicographic order.

String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi, and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languages.

The teacher gave Anna and Maria homework. She gave them a string of length n. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string "aab": "a", "a", "aa", "ab", "aab", "b"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the k-th string from the list. Help Anna and Maria do the homework.

Input

The first line contains a non-empty string that only consists of small Latin letters ("a"-"z"), whose length does not exceed 105. The second line contains the only integer k (1 ≤ k ≤ 105).

Output

Print the string Anna and Maria need — the k-th (in the lexicographical order) substring of the given string. If the total number of substrings is less than k, print a string saying "No such line." (without the quotes).

Examples

Input

aa
2

Output

a

Input

abc
5

Output

bc

Input

abab
7

Output

b

Note

In the second sample before string "bc" follow strings "a", "ab", "abc", "b".

```python
from heapq import *

l=input()

k=int(input())

n=len(l)

if k>n*(n+1)/2:

    print("No such line.")

    quit()

ss=[(l[i],i) for i in range(n)]

heapify(ss)

while k:

    k-=1

    t=heappop(ss)

    if k==0:

        print(t[0])

    else:

        if t[1]<n-1:

            heappush(ss,(t[0]+l[t[1]+1],t[1]+1))

# Made By Mostafa_Khaled
```


1332_C. K-Complete Word

Word s of length n is called k-complete if

  * s is a palindrome, i.e. s_i=s_{n+1-i} for all 1 ≤ i ≤ n;
  * s has a period of k, i.e. s_i=s_{k+i} for all 1 ≤ i ≤ n-k.

For example, "abaaba" is a 3-complete word, while "abccba" is not.

Bob is given a word s of length n consisting of only lowercase Latin letters and an integer k, such that n is divisible by k. He wants to convert s to any k-complete word.

To do this Bob can choose some i (1 ≤ i ≤ n) and replace the letter at position i with some other lowercase Latin letter.

So now Bob wants to know the minimum number of letters he has to replace to convert s to any k-complete word.

Note that Bob can do zero changes if the word s is already k-complete.

You are required to answer t test cases independently.

Input

The first line contains a single integer t (1 ≤ t≤ 10^5) — the number of test cases.

The first line of each test case contains two integers n and k (1 ≤ k < n ≤ 2 ⋅ 10^5, n is divisible by k).

The second line of each test case contains a word s of length n.

It is guaranteed that word s only contains lowercase Latin letters. And it is guaranteed that the sum of n over all test cases will not exceed 2 ⋅ 10^5.

Output

For each test case, output one integer, representing the minimum number of characters he has to replace to convert s to any k-complete word.

Example

Input

4
6 2
abaaba
6 3
abaaba
36 9
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp

Output

2
0
23
16

Note

In the first test case, one optimal solution is aaaaaa.

In the second test case, the given word itself is k-complete.

```python
import sys
input=sys.stdin.readline
t=int(input())
def find(no):
    global par
    if par[no]==no:
        return no
    par[no]=find(par[no])
    return par[no]
for _ in range(t):
    n,k=map(int,input().split())
    s=[ord(i)-97 for i in input()]

    par=[i for i in range(n)]
    vis=[0 for i in range(n)]
    for i in range(k):
        for j in range(i,n,k):

            vis[j]=1
            x=n-j-1
            aa=find(x)
            bb=find(j)
            par[bb]=aa
            if(j>i):
                aa=find(j-k)
                bb=find(j)
                par[bb]=aa
    tot=n
    aa=set(par)
    co=[[0 for i in range(26)] for j in range(n)]
   # print(par)
    for i in range(n):
        co[par[i]][s[i]]+=1
    tot-=sum([max(i) for i in co])
    print(tot)

```


1352_F. Binary String Reconstruction

For some binary string s (i.e. each character s_i is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length 2 were written. For each pair (substring of length 2), the number of '1' (ones) in it was calculated.

You are given three numbers:

  * n_0 — the number of such pairs of consecutive characters (substrings) where the number of ones equals 0;
  * n_1 — the number of such pairs of consecutive characters (substrings) where the number of ones equals 1;
  * n_2 — the number of such pairs of consecutive characters (substrings) where the number of ones equals 2.

For example, for the string s="1110011110", the following substrings would be written: "11", "11", "10", "00", "01", "11", "11", "11", "10". Thus, n_0=1, n_1=3, n_2=5.

Your task is to restore any suitable binary string s from the given values n_0, n_1, n_2. It is guaranteed that at least one of the numbers n_0, n_1, n_2 is greater than 0. Also, it is guaranteed that a solution exists.

Input

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

Each test case consists of one line which contains three integers n_0, n_1, n_2 (0 ≤ n_0, n_1, n_2 ≤ 100; n_0 + n_1 + n_2 > 0). It is guaranteed that the answer for given n_0, n_1, n_2 exists.

Output

Print t lines. Each of the lines should contain a binary string corresponding to a test case. If there are several possible solutions, print any of them.

Example

Input

7
1 3 5
1 1 1
3 9 3
0 1 0
3 1 2
0 0 3
2 0 0

Output

1110011110
0011
0110001100101011
10
0000111
1111
000

```python
for testcase in range(int(input())):
    n0, n1, n2 = map(int, input().split())
    if n1 == 0:
        if n0:
            ans = "0" * (n0 + 1)
        else:
            ans = "1" * (n2 + 1)
    else:
        ans = ["0" * (n0 + 1), "1" * (n2 + 1)]
        for i in range(n1 - 1):
            ans.append(str(i & 1))
        ans = "".join(ans)

    print(ans)
```


1372_D. Omkar and Circle

Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem!

You are given n nonnegative integers a_1, a_2, ..., a_n arranged in a circle, where n must be odd (ie. n-1 is divisible by 2). Formally, for all i such that 2 ≤ i ≤ n, the elements a_{i - 1} and a_i are considered to be adjacent, and a_n and a_1 are also considered to be adjacent. In one operation, you pick a number on the circle, replace it with the sum of the two elements adjacent to it, and then delete the two adjacent elements from the circle. This is repeated until only one number remains in the circle, which we call the circular value.

Help Danny find the maximum possible circular value after some sequences of operations.

Input

The first line contains one odd integer n (1 ≤ n < 2 ⋅ 10^5, n is odd) — the initial size of the circle.

The second line contains n integers a_{1},a_{2},...,a_{n} (0 ≤ a_{i} ≤ 10^9) — the initial numbers in the circle.

Output

Output the maximum possible circular value after applying some sequence of operations to the given circle.

Examples

Input

3
7 10 2

Output

17

Input

1
4

Output

4

Note

For the first test case, here's how a circular value of 17 is obtained:

Pick the number at index 3. The sum of adjacent elements equals 17. Delete 7 and 10 from the circle and replace 2 with 17.

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

```python
n = int(input())
a = [int(x) for x in input().split()]
if n == 1:
	print(a[0])
	exit()
evens = [a[0]]
odds = [a[1]]
for i in range(2,n):
	if i % 2 == 0:
		evens.append(evens[-1]+a[i])
	else:
		odds.append(odds[-1] + a[i])
# print(evens)
# print(odds)
maxi = 0
for i in range(len(evens)):
	score = evens[i]
	if i == 0:
		score += odds[-1]
	else:
		score += odds[-1] - odds[i-1]
	if score > maxi:
		maxi = score
for i in range(len(odds)):
	score = odds[i]
	score += evens[-1] - evens[i]
	if score > maxi:
		maxi = score
print(maxi)
```


1395_C. Boboniu and Bit Operations

Boboniu likes bit operations. He wants to play a game with you.

Boboniu gives you two sequences of non-negative integers a_1,a_2,…,a_n and b_1,b_2,…,b_m.

For each i (1≤ i≤ n), you're asked to choose a j (1≤ j≤ m) and let c_i=a_i\& b_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Note that you can pick the same j for different i's.

Find the minimum possible c_1 | c_2 | … | c_n, where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).

Input

The first line contains two integers n and m (1≤ n,m≤ 200).

The next line contains n integers a_1,a_2,…,a_n (0≤ a_i < 2^9).

The next line contains m integers b_1,b_2,…,b_m (0≤ b_i < 2^9).

Output

Print one integer: the minimum possible c_1 | c_2 | … | c_n.

Examples

Input

4 2
2 6 4 0
2 4

Output

2

Input

7 6
1 9 1 9 8 1 0
1 1 4 5 1 4

Output

0

Input

8 5
179 261 432 162 82 43 10 38
379 357 202 184 197

Output

147

Note

For the first example, we have c_1=a_1\& b_2=0, c_2=a_2\& b_1=2, c_3=a_3\& b_1=0, c_4 = a_4\& b_1=0.Thus c_1 | c_2 | c_3 |c_4 =2, and this is the minimal answer we can get.

```python
from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
from collections import deque
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
z=[]
ma=0
for i in a:
	x=float("infinity")
	for j in b:
		x=min(i&j,x)
	ma=max(x,ma)
for i in a:
	t=float("infinity")
	for j in b:
		if t==float("infinity") or ma|(i&j)<ma|t:
			t=i&j
	z.append(t)
x=z[0]
for i in z:
	x=x|i
print(x)
```


1419_E. Decryption

An agent called Cypher is decrypting a message, that contains a [composite number](https://en.wikipedia.org/wiki/Composite_number) n. All divisors of n, which are greater than 1, are placed in a circle. Cypher can choose the initial order of numbers in the circle.

In one move Cypher can choose two adjacent numbers in a circle and insert their [least common multiple](https://en.wikipedia.org/wiki/Least_common_multiple) between them. He can do that move as many times as needed.

A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.

Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.

Input

The first line contains an integer t (1 ≤ t ≤ 100) — the number of test cases. Next t lines describe each test case.

In a single line of each test case description, there is a single composite number n (4 ≤ n ≤ 10^9) — the number from the message.

It's guaranteed that the total number of divisors of n for all test cases does not exceed 2 ⋅ 10^5.

Output

For each test case in the first line output the initial order of divisors, which are greater than 1, in the circle. In the second line output, the minimal number of moves needed to decrypt the message.

If there are different possible orders with a correct answer, print any of them.

Example

Input

3
6
4
30

Output

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

Note

In the first test case 6 has three divisors, which are greater than 1: 2, 3, 6. Regardless of the initial order, numbers 2 and 3 are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes 2, 6, 3, 6, and every two adjacent numbers are not coprime.

In the second test case 4 has two divisors greater than 1: 2, 4, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.

In the third test case all divisors of 30 greater than 1 can be placed in some order so that there are no two adjacent numbers that are coprime.

```python
from sys import stdin, stdout

# 6
# 2 3 6

# 30
# 2,3,5
# 2 30 6 3 15 5 10
# 2 - (30) - 6 - 3 - 15 - 5 - 10
# P1 - (x*P1) - P1P2 - P2 - (x*P2) - P2P3 - P3 - (x*P3) - P1P3

def decryption(n):
    r1 = []
    r2 = 0

    factor_a = getfactor(n)
    prime_a = getprime(n)

    hs = set()
    prime_dic = {}

    #print(factor_a)
    #print(prime_a)

    for i in range(len(prime_a)):
        ni = (i+1)%len(prime_a)
        prime_dic[prime_a[i]] = []

        if (prime_a[i] * prime_a[ni]) not in hs:
            prime_dic[prime_a[i]].append(prime_a[i] * prime_a[ni])

        hs.add(prime_a[i])
        hs.add(prime_a[ni])
        hs.add(prime_a[i] * prime_a[ni])

    #print(prime_dic)
    # 2 4 7 14
    # special case for two prime numbers and factors > 3
    if len(factor_a) > 3 and len(prime_a) == 2:
        for fac in factor_a:
            if fac not in hs:
                p = getoneprime(fac)
                if p == prime_a[0]:
                    prime_dic[prime_a[0]] = []
                    prime_dic[prime_a[1]].append(prime_a[0] * prime_a[1])
                break

    for fac in factor_a:
        if fac in hs:
            continue

        p = getoneprime(fac)
        prime_dic[p].append(fac)
        hs.add(fac)

    for p in prime_dic:
        r1.append(p)
        prime_dic[p].reverse()
        for f in prime_dic[p]:
            r1.append(f)

    if len(factor_a) == 3 and len(prime_a) == 2:
        r2 = 1

    return [r1, r2]

def getfactor(n):

    factor_a = [n]
    i = 2
    while i*i < n:
        if n % i == 0:
            factor_a.append(i)
            factor_a.append(n//i)
        i += 1

    if i*i == n:
        factor_a.append(i)

    return factor_a

def getprime(n):

    prime_a = []
    i = 2
    while i*i <= n:
        if n % i == 0:
            prime_a.append(i)
            while n % i == 0:
                n //= i
        i += 1

    if n > 1:
        prime_a.append(n)

    return prime_a

def getoneprime(n):

    i = 2
    while i*i <= n:
        if n % i == 0:
            return i
        i += 1

    return -1

t = int(stdin.readline())
for _ in range(t):
    n = int(stdin.readline())
    res_a = decryption(n)
    stdout.write(' '.join(map(str, res_a[0])) + '\n')
    stdout.write(str(res_a[1]) + '\n')

```


1437_F. Emotional Fishermen

n fishermen have just returned from a fishing vacation. The i-th fisherman has caught a fish of weight a_i.

Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of showing fish is a permutation of integers from 1 to n). Then they show the fish they caught according to the chosen order. When a fisherman shows his fish, he might either become happy, become sad, or stay content.

Suppose a fisherman shows a fish of weight x, and the maximum weight of a previously shown fish is y (y = 0 if that fisherman is the first to show his fish). Then:

  * if x ≥ 2y, the fisherman becomes happy;
  * if 2x ≤ y, the fisherman becomes sad;
  * if none of these two conditions is met, the fisherman stays content.

Let's call an order in which the fishermen show their fish emotional if, after all fishermen show their fish according to this order, each fisherman becomes either happy or sad. Calculate the number of emotional orders modulo 998244353.

Input

The first line contains one integer n (2 ≤ n ≤ 5000).

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

Output

Print one integer — the number of emotional orders, taken modulo 998244353.

Examples

Input

4
1 1 4 9

Output

20

Input

4
4 3 2 1

Output

0

Input

3
4 2 1

Output

6

Input

8
42 1337 13 37 420 666 616 97

Output

19200

```python
from collections import defaultdict
import sys
input = sys.stdin.readline
n = int(input())
a = map(int, input().split())
mod = 998244353
d = defaultdict(int)
for x in a:
    d[x] += 1
d[0] = 0
b = list(d.items())
b.sort()
m = len(b)
ba = [0] * m
cn = [0] * (m + 1)
k = h = 0
for i, x in enumerate(b):
    while h < m and x[0] >= b[h][0] * 2:
        h += 1
    ba[i] = h - 1
    while k < m and x[0] * 2 > b[k][0]:
        k += 1
    cn[k] += x[1]
for i in range(m):
    cn[i+1] += cn[i]
dp = [0] * m
dp[0] = 1
b = [x[1] for x in b]
for i in range(n):
    ndp = [0] * m
    for j in range(1, m):
        if cn[j] >= i - 1:
            ndp[j] = dp[j] * (cn[j] - i + 1) % mod
        dp[j] += dp[j-1]
        if dp[j] >= mod:
            dp[j] -= mod
    for j in range(1, m):
        ndp[j] += dp[ba[j]] * b[j]
        ndp[j] %= mod
    dp = ndp
print(sum(dp) % mod)
```


1462_D. Add to Neighbour and Remove

Polycarp was given an array of a[1 ... n] of n integers. He can perform the following operation with the array a no more than n times:

  * Polycarp selects the index i and adds the value a_i to one of his choice of its neighbors. More formally, Polycarp adds the value of a_i to a_{i-1} or to a_{i+1} (if such a neighbor does not exist, then it is impossible to add to it).
  * After adding it, Polycarp removes the i-th element from the a array. During this step the length of a is decreased by 1.

The two items above together denote one single operation.

For example, if Polycarp has an array a = [3, 1, 6, 6, 2], then it can perform the following sequence of operations with it:

  * Polycarp selects i = 2 and adds the value a_i to (i-1)-th element: a = [4, 6, 6, 2].
  * Polycarp selects i = 1 and adds the value a_i to (i+1)-th element: a = [10, 6, 2].
  * Polycarp selects i = 3 and adds the value a_i to (i-1)-th element: a = [10, 8].
  * Polycarp selects i = 2 and adds the value a_i to (i-1)-th element: a = [18].

Note that Polycarp could stop performing operations at any time.

Polycarp wondered how many minimum operations he would need to perform to make all the elements of a equal (i.e., he wants all a_i are equal to each other).

Input

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

The first line of each test case contains a single integer n (1 ≤ n ≤ 3000) — the length of the array. The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^5) — array a.

It is guaranteed that the sum of n over all test cases does not exceed 3000.

Output

For each test case, output a single number — the minimum number of operations that Polycarp needs to perform so that all elements of the a array are the same (equal).

Example

Input

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

Output

4
2
0
2

Note

In the first test case of the example, the answer can be constructed like this (just one way among many other ways):

[3, 1, 6, 6, 2] \xrightarrow[]{i=4,~add~to~left} [3, 1, 12, 2] \xrightarrow[]{i=2,~add~to~right} [3, 13, 2] \xrightarrow[]{i=1,~add~to~right} [16, 2] \xrightarrow[]{i=2,~add~to~left} [18]. All elements of the array [18] are the same.

In the second test case of the example, the answer can be constructed like this (just one way among other ways):

[1, 2, 2, 1] \xrightarrow[]{i=1,~add~to~right} [3, 2, 1] \xrightarrow[]{i=3,~add~to~left} [3, 3]. All elements of the array [3, 3] are the same.

In the third test case of the example, Polycarp doesn't need to perform any operations since [2, 2, 2] contains equal (same) elements only.

In the fourth test case of the example, the answer can be constructed like this (just one way among other ways):

[6, 3, 2, 1] \xrightarrow[]{i=3,~add~to~right} [6, 3, 3] \xrightarrow[]{i=3,~add~to~left} [6, 6]. All elements of the array [6, 6] are the same.

```python
def check(sm):
    cur = 0
    for i in range(n):
        cur += lis[i]
        if cur == sm: cur = 0
        elif cur > sm: return False
    return cur == 0

t = int(input())
s = ""
for i in range(t):
    n = int(input())
    lis = [*map(int, input().split())]
    sm = sum(lis)
    ans = -1
    for j in range(n, 0, -1):
        if sm % j == 0 and check(sm // j):
            ans = n - j
            break
    s += f"{ans}\n"
print(s)

```


1487_E. Cheap Dinner

Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.

There are n_1 different types of first courses Ivan can buy (the i-th of them costs a_i coins), n_2 different types of second courses (the i-th of them costs b_i coins), n_3 different types of drinks (the i-th of them costs c_i coins) and n_4 different types of desserts (the i-th of them costs d_i coins).

Some dishes don't go well with each other. There are m_1 pairs of first courses and second courses that don't go well with each other, m_2 pairs of second courses and drinks, and m_3 pairs of drinks and desserts that don't go well with each other.

Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!

Input

The first line contains four integers n_1, n_2, n_3 and n_4 (1 ≤ n_i ≤ 150000) — the number of types of first courses, second courses, drinks and desserts, respectively.

Then four lines follow. The first line contains n_1 integers a_1, a_2, ..., a_{n_1} (1 ≤ a_i ≤ 10^8), where a_i is the cost of the i-th type of first course. Three next lines denote the costs of second courses, drinks, and desserts in the same way (1 ≤ b_i, c_i, d_i ≤ 10^8).

The next line contains one integer m_1 (0 ≤ m_1 ≤ 200000) — the number of pairs of first and second courses that don't go well with each other. Each of the next m_1 lines contains two integers x_i and y_i (1 ≤ x_i ≤ n_1; 1 ≤ y_i ≤ n_2) denoting that the first course number x_i doesn't go well with the second course number y_i. All these pairs are different.

The block of pairs of second dishes and drinks that don't go well with each other is given in the same format. The same for pairs of drinks and desserts that don't go well with each other (0 ≤ m_2, m_3 ≤ 200000).

Output

If it's impossible to choose a first course, a second course, a drink, and a dessert so that they go well with each other, print -1. Otherwise, print one integer — the minimum total cost of the dinner.

Examples

Input

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

Output

26

Input

1 1 1 1
1
1
1
1
1
1 1
0
0

Output

-1

Note

The best option in the first example is to take the first course 2, the second course 1, the drink 2 and the dessert 1.

In the second example, the only pair of the first course and the second course is bad, so it's impossible to have dinner.

```python
MAX_VAL = 2 ** 31

def prepare_values(vals):
    zipped_vals = list(zip(vals, range(1, len(vals) + 1)))
    zipped_vals.sort()
    pairs = [(old_i, i) for i, (val, old_i) in enumerate(zipped_vals, 1)]
    return zipped_vals, dict(pairs)

def renumber_ids(dic, l):
    return [dic[x] for x in l]

def get_first_absent(l):
    l.sort()
    i = 1
    for x in l:
        if i != x:
            return i
        i += 1

    return i

def read_mismatches():
    n = int(input())
    mismatches = dict()
    for _ in range(n):
        x, y = map(int, input().split())
        l = mismatches.get(x, [])
        l.append(y)
        mismatches[x] = l

    return n, mismatches

def accumulate_cost(to_accumulate, from_accumulate, mismatches):
    n = len(to_accumulate)

    from_zipped, from_dic = prepare_values(from_accumulate)

    for x in range(1, n + 1):
        l = mismatches.get(x, [])
        renumbered_l = renumber_ids(from_dic, l)
        first_absent = get_first_absent(renumbered_l)

        if first_absent > len(from_accumulate):
            to_accumulate[x - 1] = MAX_VAL
        else:
            to_accumulate[x - 1] += from_zipped[first_absent - 1][0]

    return 0

def solution():
    n1, n2, n3, n4 = map(int, input().split())

    first_course = list(map(int, input().split()))
    second_course = list(map(int, input().split()))
    drink = list(map(int, input().split()))
    dessert = list(map(int, input().split()))

    m1, fc_sc_mismatch = read_mismatches()
    m2, sc_drink_mismatch = read_mismatches()
    m3, drink_dessert_mismatch = read_mismatches()

    # drinks
    accumulate_cost(drink, dessert, drink_dessert_mismatch)

    # second_course
    accumulate_cost(second_course, drink, sc_drink_mismatch)

    # first course
    accumulate_cost(first_course, second_course, fc_sc_mismatch)

    result = min(first_course)
    print(-1 if result >= MAX_VAL else result)

solution()
```


1511_B. GCD Length

You are given three integers a, b and c.

Find two positive integers x and y (x > 0, y > 0) such that:

  * the decimal representation of x without leading zeroes consists of a digits;
  * the decimal representation of y without leading zeroes consists of b digits;
  * the decimal representation of gcd(x, y) without leading zeroes consists of c digits.

gcd(x, y) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x and y.

Output x and y. If there are multiple answers, output any of them.

Input

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

Each of the next t lines contains three integers a, b and c (1 ≤ a, b ≤ 9, 1 ≤ c ≤ min(a, b)) — the required lengths of the numbers.

It can be shown that the answer exists for all testcases under the given constraints.

Additional constraint on the input: all testcases are different.

Output

For each testcase print two positive integers — x and y (x > 0, y > 0) such that

  * the decimal representation of x without leading zeroes consists of a digits;
  * the decimal representation of y without leading zeroes consists of b digits;
  * the decimal representation of gcd(x, y) without leading zeroes consists of c digits.

Example

Input

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

Output

11 492
13 26
140133 160776
1 1

Note

In the example:

  1. gcd(11, 492) = 1
  2. gcd(13, 26) = 13
  3. gcd(140133, 160776) = 21
  4. gcd(1, 1) = 1


1538_G. Gift Set

Polycarp has x of red and y of blue candies. Using them, he wants to make gift sets. Each gift set contains either a red candies and b blue candies, or a blue candies and b red candies. Any candy can belong to at most one gift set.

Help Polycarp to find the largest number of gift sets he can create.

For example, if x = 10, y = 12, a = 5, and b = 2, then Polycarp can make three gift sets:

  * In the first set there will be 5 red candies and 2 blue candies;
  * In the second set there will be 5 blue candies and 2 red candies;
  * In the third set will be 5 blue candies and 2 red candies.

Note that in this example there is one red candy that Polycarp does not use in any gift set.

Input

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

Each test case consists of a single string containing four integers x, y, a, and b (1 ≤ x, y, a, b ≤ 10^9).

Output

For each test case, output one number — the maximum number of gift sets that Polycarp can make.

Example

Input

9
10 12 2 5
1 1 2 2
52 311 13 27
1000000000 1000000000 1 1
1000000000 1 1 1000000000
1 1000000000 1000000000 1
1 2 1 1
7 8 1 2
4 1 2 3

Output

3
0
4
1000000000
1
1
1
5
0

```python
import sys,io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
read = lambda: map(int,input().split())
O = []
for _ in range(int(input())):
    x,y,a,b = read()
    if a==b:
        O.append(str(min(x,y)//a))
        continue
    if a<b: a,b = b,a
    d = a-b
    L = [0,(x+y)//(a+b)+1]
    while L[1]-L[0]>1:
        M = sum(L)//2
        xv = (a*M-x)
        yv = (y-b*M)
        L[d*(yv//d)<xv or yv<0 or xv>M*d]=M
    O.append(str(L[0]))
print('\n'.join(O))
```


165_B. Burning Midnight Oil

One day a highly important task was commissioned to Vasya — writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as <image> lines, drinks another cup of tea, then he writes <image> lines and so on: <image>, <image>, <image>, ...

The expression <image> is regarded as the integral part from dividing number a by number b.

The moment the current value <image> equals 0, Vasya immediately falls asleep and he wakes up only in the morning, when the program should already be finished.

Vasya is wondering, what minimum allowable value v can take to let him write not less than n lines of code before he falls asleep.

Input

The input consists of two integers n and k, separated by spaces — the size of the program in lines and the productivity reduction coefficient, 1 ≤ n ≤ 109, 2 ≤ k ≤ 10.

Output

Print the only integer — the minimum value of v that lets Vasya write the program in one night.

Examples

Input

7 2

Output

4

Input

59 9

Output

54

Note

In the first sample the answer is v = 4. Vasya writes the code in the following portions: first 4 lines, then 2, then 1, and then Vasya falls asleep. Thus, he manages to write 4 + 2 + 1 = 7 lines in a night and complete the task.

In the second sample the answer is v = 54. Vasya writes the code in the following portions: 54, 6. The total sum is 54 + 6 = 60, that's even more than n = 59.

```python
"""
Solution to the 706B problem on CodeForces.
"""
import sys
import math

def binary_search(k, target):
    beg, end = 1, target
    while beg + 1 < end:
        number = (beg + end) // 2
        if (lambda_function(target, k, number)):
            end = number
        else:
            beg = number
    if (lambda_function(target, k, number)):
        return number
    return int(number+1)

def lambda_function(target, k, num):
    sum = 0
    count = 0
    while True:
        exp = k ** count
        sum += math.floor(num / exp)
        if int(math.floor(num / exp)) == 0:
            return False
        if sum >= target:
            return True
        count += 1

def main():
    """
    The main method.
    """
    lines, k = (int(i) for i in str(sys.stdin.readline()).split(" "))
    if (int(lines/k) == 0):
        print(lines)
    else:
        print(binary_search(k, lines))

if __name__ == "__main__":
    main()

```


186_C. Plant

Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.

<image>

Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.

Input

The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew.

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.

Output

Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).

Examples

Input

1

Output

3

Input

2

Output

10

Note

The first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.

```python
N = int(input())
result = (pow(2, N, int(1e9 + 7)) * (pow(2, N, int(1e9 + 7)) + 1)) % int(1e9+7)
result = (result * pow(2, int(1e9+5), int(1e9+7))) % int(1e9+7)
print(result)

```


207_D5. The Beaver's Problem - 3

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

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

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

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

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

Input

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

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

Output

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

Examples


281_C. Rectangle Puzzle

You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle α.

<image>

Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.

Input

The first line contains three integers w, h, α (1 ≤ w, h ≤ 106; 0 ≤ α ≤ 180). Angle α is given in degrees.

Output

In a single line print a real number — the area of the region which belongs to both given rectangles.

The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.

Examples

Input

1 1 45

Output

0.828427125

Input

6 4 30

Output

19.668384925

Note

The second sample has been drawn on the picture above.

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

def main():
    pass

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

def binary(n):
    return (bin(n).replace("0b", ""))

def decimal(s):
    return (int(s, 2))

def pow2(n):
    p = 0
    while (n > 1):
        n //= 2
        p += 1
    return (p)

def primeFactors(n):
    l=[]
    while n % 2 == 0:
        l.append(2)
        n = n / 2
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        while n % i == 0:
            l.append(i)
            n = n / i
    if n > 2:
        l.append(int(n))
    return (l)

def isPrime(n):
    if (n == 1):
        return (False)
    else:
        root = int(n ** 0.5)
        root += 1
        for i in range(2, root):
            if (n % i == 0):
                return (False)
        return (True)

def maxPrimeFactors(n):
    maxPrime = -1
    while n % 2 == 0:
        maxPrime = 2
        n >>= 1
    for i in range(3, int(math.sqrt(n)) + 1, 2):
        while n % i == 0:
            maxPrime = i
            n = n / i
    if n > 2:
        maxPrime = n
    return int(maxPrime)

w,h,a=map(int,input().split())
if(a==0 or a==180):
    print(w*h)
else:
    w,h=max(w,h),min(w,h)
    if(a>90):
        a=180-a
    a=(a*math.pi)/180
    #print(h*(1+math.cos(a)),w*math.sin(a))
    if(h*(1+math.cos(a))< w*math.sin(a)):
        print(pow(h,2)/math.sin(a))
    else:
        #print("HEY")
        #print(math.sin(a))
        x=h-w*((math.cos(a)+1)/math.sin(a))
        t=math.tan(a)-((math.cos(a)+1)*(math.cos(a)+1)/(math.cos(a)*math.sin(a)))
        x=x/t
        x=abs(x)
        b2=w-x-(x/math.cos(a))
        b2=abs(b2)
        h2=b2/math.tan(a)
        h2=abs(h2)
        h1=h-h2-(h2/math.cos(a))
        h1=abs(h1)
        tbm=((x*h1)+(b2*h2))
        #print(x,h1,h2,b2)
        print((h*w)-tbm)
```


304_B. Calendar

Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows:

Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year.

<image>

In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February.

Look at the sample to understand what borders are included in the aswer.

Input

The first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≤ yyyy ≤ 2038 and yyyy:mm:dd is a legal date).

Output

Print a single integer — the answer to the problem.

Examples

Input

1900:01:01
2038:12:31

Output

50768

Input

1996:03:09
1991:11:12

Output

1579

```python
import sys
import datetime

y1, m1, d1 = map(int, input().split(':'))
y2, m2, d2 = map(int, input().split(':'))

print(abs((datetime.date(y1, m1, d1) - datetime.date(y2, m2, d2)).days))

```


330_C. Purification

You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n × n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:

The cleaning of all evil will awaken the door!

Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.

The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile — then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.

You would like to purify all n × n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell.

Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.

Input

The first line will contain a single integer n (1 ≤ n ≤ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise.

Output

If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell.

Examples

Input

3
.E.
E.E
.E.

Output

1 1
2 2
3 3

Input

3
EEE
E..
E.E

Output

-1

Input

5
EE.EE
E.EE.
E...E
.EE.E
EE.EE

Output

3 3
1 3
2 2
4 4
5 3

Note

The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously.

<image>

In the second example, it is impossible to purify the cell located at row 1 and column 1.

For the third example:

<image>

```python
n = int(input())
grid = [input() for line in range(n)]
total = sum([ln.count('.') for ln in grid])
rowsWSpcN = len([True for ln in grid if '.' in ln])
colsWSpcN = len([True for col in range(n) if '.' in [ln[col] for ln in grid]])
rowsWSpc = [ln.count('.') for ln in grid]
colsWSpc = [[ln[col] for ln in grid].count('.') for col in range(n)]
#print(rowsWSpc,colsWSpc)
used = 0
if 0 in rowsWSpc and 0 in colsWSpc:
    print(-1)
elif 0 not in rowsWSpc:
    for row in range(n):
        print(row+1,grid[row].index('.')+1)
else:
    for col in range(n):
        print([grid[row][col] for row in range(n)].index('.')+1,col+1)
#assert total == used
#print(used)
#print('\n'.join(['%s %s'%(str(col+1),str(row+1)) for col,row in used]))

```


352_A. Jeff and Digits

Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?

Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.

Input

The first line contains integer n (1 ≤ n ≤ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card.

Output

In a single line print the answer to the problem — the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1.

Examples

Input

4
5 0 5 0

Output

0

Input

11
5 5 5 5 5 5 5 5 0 5 5

Output

5555555550

Note

In the first test you can make only one number that is a multiple of 90 — 0.

In the second test you can make number 5555555550, it is a multiple of 90.

```python
import collections
n = int(input())
l = list(map(int,input().split()))
s = ""
if 0 in l:
    c1 = collections.Counter(l)
    s+=('0'*c1[0])

    x = (c1[5]//9)*9
    s = ('5'*x) + s
    print(int(s))
else:
    print(-1)

```


376_B. I.O.U.

Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.

This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.

Input

The first line contains two integers n and m (1 ≤ n ≤ 100; 0 ≤ m ≤ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ ci ≤ 100), which mean that person ai owes person bi ci rubles.

Assume that the people are numbered by integers from 1 to n.

It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x).

Output

Print a single integer — the minimum sum of debts in the optimal rearrangement.

Examples

Input

5 3
1 2 10
2 3 1
2 4 1

Output

10

Input

3 0

Output

0

Input

4 3
1 2 1
2 3 1
3 1 1

Output

0

Note

In the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10.

In the second sample, there are no debts.

In the third sample, you can annul all the debts.

```python
n,m = map(int, input().split())
debt=[0]*(n+1)
for i in range(m):
	a,b,c = map(int, input().split())
	debt[a]-=c
	debt[b]+=c
ans=0
for i in debt:
	if i>0:
		ans+=i
print(ans)

```


447_C. DZY Loves Sequences

DZY has a sequence a, consisting of n integers.

We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment.

Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.

You only need to output the length of the subsegment you find.

Input

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Output

In a single line print the answer to the problem — the maximum length of the required subsegment.

Examples

Input

6
7 2 3 1 5 6

Output

5

Note

You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.

```python
"""
                            pppppppppppppppppppp
                         ppppp  ppppppppppppppppppp
                      ppppppp    ppppppppppppppppppppp
                      pppppppp  pppppppppppppppppppppp
                      pppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppppp
       ppppppppppppppppppppppppppppppppppppppppppppppp  pppppppppppppppppppp
      pppppppppppppppppppppppppppppppppppppppppppppppp  ppppppppppppppppppppp
     ppppppppppppppppppppppppppppppppppppppppppppppppp  pppppppppppppppppppppp
    ppppppppppppppppppppppppppppppppppppppppppppppp    pppppppppppppppppppppppp
   pppppppppppppppppppppppppppppppppppppppppppppp     pppppppppppppppppppppppppp
  ppppppppppppppppppppppppppppppppppppppppppppp      pppppppppppppppppppppppppppp
  pppppppppppppppppppppppppppppppp               pppppppppppppppppppppppppppppppp
  pppppppppppppppppppppppppppp     pppppppppppppppppppppppppppppppppppppppppppppp
  ppppppppppppppppppppppppppp    pppppppppppppppppppppppppppppppppppppppppppppppp
    pppppppppppppppppppppppp  pppppppppppppppppppppppppppppppppppppppppppppppppp
     ppppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppppppp
      pppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppppp
       ppppppppppppppppppppp  ppppppppppppppppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppppp
                              pppppppppppppppppppppppppppppppp
                              pppppppppppppppppppppp  pppppppp
                              ppppppppppppppppppppp    ppppppp
                                 ppppppppppppppppppp  ppppp
                                    pppppppppppppppppppp
"""

import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
# sys.setrecursionlimit(pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(var): sys.stdout.write(str(var))
def outa(*var, end="\n"): sys.stdout.write(' '.join(map(str, var)) + end)
def l(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]

n = int(data())
arr = l()
if len(arr) <= 2:
    out(n)
    exit()
suf, pref = [1] * n, [1] * n
for i in range(1, n):
    if arr[i] > arr[i-1]:
        suf[i] = suf[i-1] + 1
for i in range(n-2, -1, -1):
    if arr[i] < arr[i+1]:
        pref[i] = pref[i+1] + 1
answer = max(suf)
if answer < n:
    answer += 1
for i in range(1, n-1):
    if arr[i-1] + 1 < arr[i+1]:
        answer = max(answer, suf[i-1] + 1 + pref[i+1])
out(answer)

```


469_D. Two Sets

Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied:

  * If number x belongs to set A, then number a - x must also belong to set A.
  * If number x belongs to set B, then number b - x must also belong to set B.

Help Little X divide the numbers into two sets or determine that it's impossible.

Input

The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≤ pi ≤ 109).

Output

If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B.

If it's impossible, print "NO" (without the quotes).

Examples

Input

4 5 9
2 3 4 5

Output

YES
0 0 1 1

Input

3 3 4
1 2 4

Output

NO

Note

It's OK if all the numbers are in the same set, and the other one is empty.

```python
class DisjointSet:
    def __init__(self, n):
        self._fa = list(range(n))
    def union(self, x, y):
        x = self.get_father(x)
        y = self.get_father(y)
        self._fa[x] = y
        return y
    def get_father(self, x):
        y = self._fa[x]
        if self._fa[y] == y:
            return y
        else:
            z = self._fa[y] = self.get_father(y)
            return z
    def __repr__(self):
        return repr([self.get_father(i) for i in range(len(self._fa))])

def solve(n, a, b, xs):
    h = {x: i for i, x in enumerate(xs)}
    if a == b:
        if all(a - x in h for x in xs):
            return [0] * n
        return False
    g1 = n
    g2 = n + 1
    ds = DisjointSet(n + 2)
    for i, x in enumerate(xs):
        for t in (a, b):
            if t - x in h:
                ds.union(i, h[t-x])
    for i, x in enumerate(xs):
        b1 = (a - x) in h
        b2 = (b - x) in h
        if b1 + b2 == 0:
            return False
        if b1 + b2 == 1:
            if b1:
                ds.union(i, g1)
            else:
                ds.union(i, g2)
            if ds.get_father(g1) == ds.get_father(g2):
                return False
    group = [None] * n
    for i, x in enumerate(xs):
        f = ds.get_father(i)
        if f < n:
            return False
        group[i] = f - n
    return group

n, a, b = map(int, input().split())
xs = list(map(int, input().split()))
group = solve(n, a, b, xs)
if isinstance(group, list):
    print('YES')
    print('  '.join(map(str, group)))
else:
    print('NO')

```


542_E. Playing on Graph

Vova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task.

Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (n - 1) vertices.

Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (k ≥ 0) is a connected graph whose vertices can be numbered with integers from 1 to k + 1 so that the edges of the graph connect all pairs of vertices (i, i + 1) (1 ≤ i ≤ k) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction.

<image> The picture illustrates the contraction of two vertices marked by red.

Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain.

Input

The first line contains two integers n, m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the original graph.

Next m lines contain the descriptions of edges in the format ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes.

Output

If it is impossible to obtain a chain from the given graph, print  - 1. Otherwise, print the maximum possible number of edges in the resulting chain.

Examples

Input

5 4
1 2
2 3
3 4
3 5

Output

3

Input

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

Output

-1

Input

4 2
1 3
2 4

Output

2

Note

In the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3.

In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result.

In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2.

```python
def solve():
    n, m = input().split()
    n = int(n)
    m = int(m)
    global maxValue
    maxValue = n*2
    graph = [[] for _ in range(0, n)]
    edges = []
    diameters = []
    for _ in range(0, m):
        u, v = input().split()
        u = int(u)-1
        v = int(v)-1
        edges.append(v)
        graph[u].append(v)
        graph[v].append(u)

    distance = [maxValue]*n
    queueCc = [0]*n
    queue = [0]*n
    for i in range(0, n):
        if distance[i] == maxValue:
            qlen = bfs_2k(graph, i, distance, queueCc)
            if(qlen == None):
                print(-1)
                return
            diameters.append(distance[queueCc[qlen-1]] if qlen > 0 else 0)
            for v in range(1, qlen):
                newDistance = [maxValue]*n
                bfs_2k(graph, queueCc[v], newDistance, queue)
                diameters[-1] = max(diameters[-1], newDistance[queue[qlen-1]])
    print(sum(diameters))

def bfs_2k(graph, initVertex, dist, queue):
    dist[initVertex] = 0
    queue[0] = initVertex
    qlen = qcount = 1
    i = 0
    while qcount:
        u = queue[i]
        qcount -= 1
        i += 1
        for v in graph[u]:
            if(dist[v] == maxValue):
                dist[v] = dist[u] + 1
                queue[qlen] = v
                qlen += 1
                qcount+=1
            if (dist[u] - dist[v]) % 2 == 0:
                return  None
    return  qlen

solve()

```


56_A. Bar

According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks?

The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE

Input

The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators.

Only the drinks from the list given above should be considered alcohol.

Output

Print a single number which is the number of people Vasya should check to guarantee the law enforcement.

Examples

Input

5
18
VODKA
COKE
19
17

Output

2

Note

In the sample test the second and fifth clients should be checked.

```python
a=['ABSINTH','BEER','BRANDY','CHAMPAGNE', 'GIN', 'RUM', 'SAKE', 'TEQUILA', 'VODKA', 'WHISKEY', 'WINE']
l=0
for i in range(int(input())):
    x=input()
    try:
        if(int(x)<18):
            l+=1
    except:
        if(x in a):
            l+=1
print(l)
```


612_C. Replace To Make Regular Bracket Sequence

You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.

The following definition of a regular bracket sequence is well-known, so you can be familiar with it.

Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.

For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.

Determine the least number of replaces to make the string s RBS.

Input

The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.

Output

If it's impossible to get RBS from s print Impossible.

Otherwise print the least number of replaces needed to get RBS from s.

Examples

Input

[<}){}

Output

2

Input

{()}[]

Output

0

Input

]]

Output

Impossible

```python
s = input()

stack = []
res = 0
for c in s:
    if c in '(<[{':
        stack.append(c)
    else:
        if not stack:
            print('Impossible')
            break
        last = stack.pop()
        if last + c not in ('[]', '()', '<>', '{}'):
            res += 1
else:
    if stack:
        print('Impossible')
    else:
        print(res)

```


632_C. The Smallest String Concatenation

You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.

Given the list of strings, output the lexicographically smallest concatenation.

Input

The first line contains integer n — the number of strings (1 ≤ n ≤ 5·104).

Each of the next n lines contains one string ai (1 ≤ |ai| ≤ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5·104.

Output

Print the only string a — the lexicographically smallest string concatenation.

Examples

Input

4
abba
abacaba
bcd
er

Output

abacabaabbabcder

Input

5
x
xx
xxa
xxaa
xxaaa

Output

xxaaaxxaaxxaxxx

Input

3
c
cb
cba

Output

cbacbc

```python
from functools import cmp_to_key

def comparator(a,b):
    return -1 if a+b <= b+a else 1

def smallest_string(str_list):
    return "".join(sorted(str_list, key=cmp_to_key(comparator)))

if __name__ == '__main__':
    n = int(input())
    str_list = []
    for _ in range(n):
        s = input()
        str_list.append(s)
    print(smallest_string(str_list))

```


750_B. New Year and North Pole

In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers.

Limak, a polar bear, lives on the North Pole. Close to the New Year, he helps somebody with delivering packages all around the world. Instead of coordinates of places to visit, Limak got a description how he should move, assuming that he starts from the North Pole. The description consists of n parts. In the i-th part of his journey, Limak should move ti kilometers in the direction represented by a string diri that is one of: "North", "South", "West", "East".

Limak isn’t sure whether the description is valid. You must help him to check the following conditions:

  * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the North Pole, he can move only to the South.
  * If at any moment of time (before any of the instructions or while performing one of them) Limak is on the South Pole, he can move only to the North.
  * The journey must end on the North Pole.

Check if the above conditions are satisfied and print "YES" or "NO" on a single line.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 50).

The i-th of next n lines contains an integer ti and a string diri (1 ≤ ti ≤ 106, <image>) — the length and the direction of the i-th part of the journey, according to the description Limak got.

Output

Print "YES" if the description satisfies the three conditions, otherwise print "NO", both without the quotes.

Examples

Input

5
7500 South
10000 East
3500 North
4444 West
4000 North

Output

YES

Input

2
15000 South
4000 East

Output

NO

Input

5
20000 South
1000 North
1000000 West
9000 North
10000 North

Output

YES

Input

3
20000 South
10 East
20000 North

Output

NO

Input

2
1000 North
1000 South

Output

NO

Input

4
50 South
50 North
15000 South
15000 North

Output

YES

Note

Drawings below show how Limak's journey would look like in first two samples. In the second sample the answer is "NO" because he doesn't end on the North Pole.

<image>

```python
n = int(input())
x = 0
y = 0
fl = True
for i in range(n):
    ar = input().split()
    d = int(ar[0])
    if fl:
        if x == 0 and ar[1] != 'South':
            fl = False
        if x == 20000 and ar[1] != 'North':
            fl = False
        if ar[1][0] == 'S':
            if x + d > 20000:
                fl = False
            else:
                x += d
        if ar[1][0] == 'N':
            if x - d < 0:
                fl = False
            else:
                x -= d
        if ar[1][0] == 'E':
            y = (x + d) % 40000
        if ar[1][0] == 'W':
            y = (40000 + x - d) % 40000
if x != 0 or not fl:
    print('NO')
else:
    print('YES')
```


818_G. Four Melodies

Author note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult!

Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks.

This time Alice wants to form four melodies for her tracks.

Alice has a sheet with n notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal.

Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7.

You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody.

Input

The first line contains one integer number n (4 ≤ n ≤ 3000).

The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — notes written on a sheet.

Output

Print maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody.

Examples

Input

5
1 3 5 7 9

Output

4

Input

5
1 3 5 7 2

Output

5

Note

In the first example it is possible to compose 4 melodies by choosing any 4 notes (and each melody will consist of only one note).

In the second example it is possible to compose one melody with 2 notes — {1, 2}. Remaining notes are used in other three melodies (one note per each melody).

```python
import sys

n = int(sys.stdin.readline())
a = [0] + [int(i) for i in sys.stdin.readline().split()]

dp = [[0]*(n + 1) for i in range(n + 1)]
ans = 0

maxnum = [0] * (10**5 + 2)
maxmod = [0] * 7

for y in range(n + 1):
    maxmod = [0] * 7

    for ai in a:
        maxnum[ai] = 0

    for i in range(y):
        maxmod[a[i] % 7] = max(maxmod[a[i] % 7], dp[i][y])
        maxnum[a[i]] = max(maxnum[a[i]], dp[i][y])

    for x in range(y + 1, n + 1):
        dp[x][y] = max(maxmod[a[x] % 7], maxnum[a[x] + 1], maxnum[a[x] - 1], dp[0][y]) + 1
        dp[y][x] = dp[x][y]
        maxmod[a[x] % 7] = max(maxmod[a[x] % 7], dp[x][y])
        maxnum[a[x]] = max(maxnum[a[x]], dp[x][y])
        ans = max(ans, dp[x][y])

print(ans)

```


844_C. Sorting by Subsequences

You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.

Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.

Every element of the sequence must appear in exactly one subsequence.

Input

The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence.

The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.

Output

In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements.

In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence.

Indices could be printed in any order. Every index from 1 to n must appear in output exactly once.

If there are several possible answers, print any of them.

Examples

Input

6
3 2 1 6 5 4

Output

4
2 1 3
1 2
2 4 6
1 5

Input

6
83 -75 -49 11 37 62

Output

1
6 1 2 3 4 5 6

Note

In the first sample output:

After sorting the first subsequence we will get sequence 1 2 3 6 5 4.

Sorting the second subsequence changes nothing.

After sorting the third subsequence we will get sequence 1 2 3 4 5 6.

Sorting the last subsequence changes nothing.

```python
n = int(input())
a = list(map(int, input().split()))
a = sorted(range(n), key=lambda i: a[i])
s = []
for i in range(n):
    if a[i] + 1:
        l = []
        s.append(l)
        while a[i] + 1:
            l.append(i + 1)
            a[i], i = -1, a[i]

print(len(s))
for l in s:
    print(len(l), *l)

```


913_C. Party Lemonade

A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.

Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2i - 1 liters and costs ci roubles. The number of bottles of each type in the store can be considered infinite.

You want to buy at least L liters of lemonade. How many roubles do you have to spend?

Input

The first line contains two integers n and L (1 ≤ n ≤ 30; 1 ≤ L ≤ 109) — the number of types of bottles in the store and the required amount of lemonade in liters, respectively.

The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 109) — the costs of bottles of different types.

Output

Output a single integer — the smallest number of roubles you have to pay in order to buy at least L liters of lemonade.

Examples

Input

4 12
20 30 70 90

Output

150

Input

4 3
10000 1000 100 10

Output

10

Input

4 3
10 100 1000 10000

Output

30

Input

5 787787787
123456789 234567890 345678901 456789012 987654321

Output

44981600785557577

Note

In the first example you should buy one 8-liter bottle for 90 roubles and two 2-liter bottles for 30 roubles each. In total you'll get 12 liters of lemonade for just 150 roubles.

In the second example, even though you need only 3 liters, it's cheaper to buy a single 8-liter bottle for 10 roubles.

In the third example it's best to buy three 1-liter bottles for 10 roubles each, getting three liters for 30 roubles.

```python
n = input().split()
l = int(n[1])
n = int(n[0])
c = input().split()
cperl = []
for i in range(n):
    c[i] = int(c[i])
    cperl.append([(c[i])/2**i, 2**i, i])
cperl.sort()
f = False
nl = [0]
nc = [0]
i = 0
while not f:
    p = nl[i]
    nl[i] += cperl[i][1] * ((l-p)//cperl[i][1])
    nc[i] += c[cperl[i][2]] * ((l-p)//cperl[i][1])
    if nl[i] == l:
        f = True
        break
    nl.append(nl[i])
    nc.append(nc[i])
    nl[i] += cperl[i][1]
    nc[i] += c[cperl[i][2]]
    i += 1
    if i == n:
        break
print(min(nc))
```


935_C. Fifa and Fafa

Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius R. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.

The world is represented as an infinite 2D plane. The flat is centered at (x1, y1) and has radius R and Fafa's laptop is located at (x2, y2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area.

Input

The single line of the input contains 5 space-separated integers R, x1, y1, x2, y2 (1 ≤ R ≤ 105, |x1|, |y1|, |x2|, |y2| ≤ 105).

Output

Print three space-separated numbers xap, yap, r where (xap, yap) is the position which Fifa chose for the access point and r is the radius of its range.

Your answer will be considered correct if the radius does not differ from optimal more than 10 - 6 absolutely or relatively, and also the radius you printed can be changed by no more than 10 - 6 (absolutely or relatively) in such a way that all points outside the flat and Fafa's laptop position are outside circle of the access point range.

Examples

Input

5 3 3 1 1

Output

3.7677669529663684 3.7677669529663684 3.914213562373095

Input

10 5 5 5 15

Output

5.0 5.0 10.0

```python
import math
i,x1,y1,x2,y2=input().split()
R=int(i)
x=int(x1)
y=int(y1)
xx=int(x2)
yy=int(y2)
a=(x-xx)*(x-xx)
b=(y-yy)*(y-yy)
d=math.sqrt(a+b)
flag=0
if a+b >= R*R:
    print(x,end=" ")
    print(y,end=" ")
    print(R)
    flag=1
elif flag!=1 and d!=0:
    r=(d+R)/2
    t=xx + r*(x-xx)/d
    u=yy + r*(y-yy)/d
    print(t,end=" ")
    print(u,end=" ")
    print(r)
if d==0:
    r=R/2
    s=x-r
    v=y
    print(s,end=" ")
    print(v,end=" ")
    print(r)
```


961_B. Lecture Sleep

Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.

Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — ai during the i-th minute. Otherwise he writes nothing.

You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that <image> and will write down all the theorems lecturer tells.

You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.

Input

The first line of the input contains two integer numbers n and k (1 ≤ k ≤ n ≤ 105) — the duration of the lecture in minutes and the number of minutes you can keep Mishka awake.

The second line of the input contains n integer numbers a1, a2, ... an (1 ≤ ai ≤ 104) — the number of theorems lecturer tells during the i-th minute.

The third line of the input contains n integer numbers t1, t2, ... tn (0 ≤ ti ≤ 1) — type of Mishka's behavior at the i-th minute of the lecture.

Output

Print only one integer — the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.

Example

Input

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

Output

16

Note

In the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.

```python
from collections import Counter

def main():
    n, k = list(map(int, input().split()))
    a = list(map(int, input().split()))
    t = list(map(int, input().split()))
    print(solve(n, k, a, t))

def solve(n, k, a, t):
    minsum = sum(ai for ai, ti in zip(a,t) if ti == 1)
    inc = sum(ai for ai, ti in zip(a[:k], t[:k]) if ti == 0)
    best_inc = inc
    for i in range(1, n - k + 1):
        if t[i - 1] == 0:
            inc -= a[i - 1]
        if t[i + k - 1] == 0:
            inc += a[i + k - 1]
        if inc > best_inc:
            best_inc = inc
    return minsum + best_inc

main()

```


989_A. A Blend of Springtime

When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead.

"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."

"But these blends are at their best, aren't they?" Absorbed in the landscape, Kanno remains optimistic.

The landscape can be expressed as a row of consecutive cells, each of which either contains a flower of colour amber or buff or canary yellow, or is empty.

When a flower withers, it disappears from the cell that it originally belonged to, and it spreads petals of its colour in its two neighbouring cells (or outside the field if the cell is on the side of the landscape). In case petals fall outside the given cells, they simply become invisible.

You are to help Kanno determine whether it's possible that after some (possibly none or all) flowers shed their petals, at least one of the cells contains all three colours, considering both petals and flowers. Note that flowers can wither in arbitrary order.

Input

The first and only line of input contains a non-empty string s consisting of uppercase English letters 'A', 'B', 'C' and characters '.' (dots) only (\lvert s \rvert ≤ 100) — denoting cells containing an amber flower, a buff one, a canary yellow one, and no flowers, respectively.

Output

Output "Yes" if it's possible that all three colours appear in some cell, and "No" otherwise.

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

Examples

Input

.BAC.

Output

Yes

Input

AA..CB

Output

No

Note

In the first example, the buff and canary yellow flowers can leave their petals in the central cell, blending all three colours in it.

In the second example, it's impossible to satisfy the requirement because there is no way that amber and buff meet in any cell.

```python
s=input()
f=False
for i in range(len(s)-2):
    t=s[i:i+3]
    if 'A' in t and 'B' in t and 'C' in t:
        f=True
if f:
    print('YES')
else:
    print('NO')
```


p02599 AtCoder Beginner Contest 174 - Range Set Query

We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.

You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

Constraints

* 1\leq N,Q \leq 5 \times 10^5
* 1\leq c_i \leq N
* 1\leq l_i \leq r_i \leq N
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the response to the i-th query.

Examples

Input

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

Output

2
3
1

Input

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

Output

1
2
2
1
2
2
6
3
3
3

```python
import sys
input=sys.stdin.readline
n,q=map(int,input().split())
c=list(map(int,input().split()))
l=[list(map(int,input().split())) for i in range(q)]
for i in range(q):
  l[i].append(i)
l.sort(key=lambda x:x[1])

L=[-1]*(5*10**5+1)

class Bit:
  def __init__(self,n):
    self.size=n
    self.tree=[0]*(n + 1)
    self.depth=n.bit_length()

  def sum(self,i):
    s=0
    while i>0:
      s+=self.tree[i]
      i-=i&-i
    return s

  def add(self,i,x):
    while i<=self.size:
      self.tree[i]+=x
      i+=i&-i

BIT=Bit(n+1)

ans=[0]*q
ct=0
for i in range(q):
  while ct<=l[i][1]:
    if L[c[ct-1]-1]!=-1:
      BIT.add(L[c[ct-1]-1],-1)
    L[c[ct-1]-1]=ct+1
    BIT.add(ct+1,1)
    ct+=1
  ans[l[i][2]]=BIT.sum(l[i][1]+1)-BIT.sum(l[i][0])

for i in range(q):
  print(ans[i])
```


p02730 AtCoder Beginner Contest 159 - String Palindrome

A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied:

* S is a palindrome.
* Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome.
* The string consisting of the (N+3)/2-st through N-th characters of S is a palindrome.

Determine whether S is a strong palindrome.

Constraints

* S consists of lowercase English letters.
* The length of S is an odd number between 3 and 99 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

If S is a strong palindrome, print `Yes`; otherwise, print `No`.

Examples

Input

akasaka

Output

Yes

Input

level

Output

No

Input

atcoder

Output

No


p02863 AtCoder Beginner Contest 145 - All-you-can-eat

Takahashi is at an all-you-can-eat restaurant.

The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.

The restaurant has the following rules:

* You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.
* You cannot order the same kind of dish more than once.
* Until you finish eating the dish already served, you cannot order a new dish.
* After T-0.5 minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.

Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.

What is the maximum possible happiness achieved by making optimal choices?

Constraints

* 2 \leq N \leq 3000
* 1 \leq T \leq 3000
* 1 \leq A_i \leq 3000
* 1 \leq B_i \leq 3000
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N T
A_1 B_1
:
A_N B_N

Output

Print the maximum possible happiness Takahashi can achieve.

Examples

Input

2 60
10 10
100 100

Output

110

Input

3 60
10 10
10 20
10 30

Output

60

Input

3 60
30 10
30 20
30 30

Output

50

Input

10 100
15 23
20 18
13 17
24 12
18 29
19 27
23 21
18 20
27 15
22 25

Output

145

```python
n, t = map(int, input().split())
items = [tuple(map(int, input().split())) for _ in range(n)]
items.sort()
ma = items[-1][0]
dp = [0] * (t+ma)

for a, b in items:
    for i in range(t+ma-1, a-1, -1):
        if i-a < t:
            dp[i] = max(dp[i], dp[i-a] + b)

print(max(dp))

```


p02998 AtCoder Beginner Contest 131 - Must Be Rectangular!

There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i).

We will repeat the following operation as long as possible:

* Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at the remaining position.

We can prove that we can only do this operation a finite number of times. Find the maximum number of times we can do the operation.

Constraints

* 1 \leq N \leq 10^5
* 1 \leq x_i, y_i \leq 10^5
* If i \neq j, x_i \neq x_j or y_i \neq y_j.
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the maximum number of times we can do the operation.

Examples

Input

3
1 1
5 1
5 5

Output

1

Input

2
10 10
20 20

Output

0

Input

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

Output

16

```python
import sys
input = sys.stdin.readline
M = 10**5

n = int(input())
G = [[] for _ in range(2*M+1)]
for _ in range(n):
  x, y = map(int, input().split())
  G[x].append(y+M)
  G[y+M].append(x)
seen = [False]*(2*M+1)
def dfs(v):
  stack = [v]
  seen[v] = True
  cnt_x, cnt_y = 0, 0
  while stack:
    v = stack.pop()
    if v <= M:
      cnt_x += 1
    else:
      cnt_y += 1
    for nv in G[v]:
      if seen[nv]:
        continue
      seen[nv] = True
      stack.append(nv)
  return cnt_x*cnt_y
ans = 0
for i in range(2*M+1):
  if not seen[i]:
    ans += dfs(i)
ans -= n
print(ans)
```


p03139 NIKKEI Programming Contest 2019 - Subscribers

We conducted a survey on newspaper subscriptions. More specifically, we asked each of the N respondents the following two questions:

* Question 1: Are you subscribing to Newspaper X?
* Question 2: Are you subscribing to Newspaper Y?

As the result, A respondents answered "yes" to Question 1, and B respondents answered "yes" to Question 2.

What are the maximum possible number and the minimum possible number of respondents subscribing to both newspapers X and Y?

Write a program to answer this question.

Constraints

* 1 \leq N \leq 100
* 0 \leq A \leq N
* 0 \leq B \leq N
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the maximum possible number and the minimum possible number of respondents subscribing to both newspapers, in this order, with a space in between.

Examples

Input

10 3 5

Output

3 0

Input

10 7 5

Output

5 2

Input

100 100 100

Output

100 100

```python
n,a,b=map(int,input().split())
and_=min(a,b)
or_=max(0, a+b-n)
print(and_, or_)
```


p03283 AtCoder Beginner Contest 106 - AtCoder Express 2

In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters:

* The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.

Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.

Constraints

* N is an integer between 1 and 500 (inclusive).
* M is an integer between 1 and 200 \ 000 (inclusive).
* Q is an integer between 1 and 100 \ 000 (inclusive).
* 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)
* 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q

Output

Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.

Examples

Input

2 3 1
1 1
1 2
2 2
1 2

Output

3

Input

10 3 2
1 5
2 8
7 10
1 7
3 10

Output

1
1

Input

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

Output

7
9
10
6
8
9
6
7
8
10

```python
n,m,q=map(int,input().split())
a=[[0 for _ in range(n)] for _ in range(n)]

for i in range(m):
  x,y=map(int,input().split())
  a[x-1][y-1]+=1

for j in range(n):
  for k in range(1,n):
    a[j][k]=a[j][k]+a[j][k-1]

for l in range(q):
  ans=0
  L,R=map(int,input().split())
  for g in range(L-1,R):
    ans+=a[g][R-1]
  print(ans)
```


p03438 AtCoder Petrozavodsk Contest 001 - Two Arrays

You are given two integer sequences of length N: a_1,a_2,..,a_N and b_1,b_2,..,b_N. Determine if we can repeat the following operation zero or more times so that the sequences a and b become equal.

Operation: Choose two integers i and j (possibly the same) between 1 and N (inclusive), then perform the following two actions simultaneously:

* Add 2 to a_i.
* Add 1 to b_j.

Constraints

* 1 ≤ N ≤ 10 000
* 0 ≤ a_i,b_i ≤ 10^9 (1 ≤ i ≤ N)
* All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 .. a_N
b_1 b_2 .. b_N

Output

If we can repeat the operation zero or more times so that the sequences a and b become equal, print `Yes`; otherwise, print `No`.

Examples

Input

3
1 2 3
5 2 2

Output

Yes

Input

5
3 1 4 1 5
2 7 1 8 2

Output

No

Input

5
2 7 1 8 2
3 1 4 1 5

Output

No

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

x=sum(b)-sum(a)
y=0
for i in range(n):
    if a[i]<b[i]:
        y+=-((a[i]-b[i])//2)
print("No" if x<y else "Yes")
```


p03597 AtCoder Beginner Contest 074 - Bichrome Cells

We have an N \times N square grid.

We will paint each square in the grid either black or white.

If we paint exactly A squares white, how many squares will be painted black?

Constraints

* 1 \leq N \leq 100
* 0 \leq A \leq N^2

Inputs

Input is given from Standard Input in the following format:

N
A

Outputs

Print the number of squares that will be painted black.

Examples

Input

3
4

Output

5

Input

19
100

Output

261

Input

10
0

Output

100

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


p00021 Parallelism

There are four points: $A(x_1, y_1)$, $B(x_2, y_2)$, $C(x_3, y_3)$, and $D(x_4, y_4)$. Write a program which determines whether the line $AB$ and the line $CD$ are parallel. If those two lines are parallel, your program should prints "YES" and if not prints "NO".

Input

Input consists of several datasets. In the first line, you are given the number of datasets $n$ ($n \leq 100$). There will be $n$ lines where each line correspondgs to each dataset. Each dataset consists of eight real numbers:

$x_1$ $y_1$ $x_2$ $y_2$ $x_3$ $y_3$ $x_4$ $y_4$

You can assume that $-100 \leq x_1, y_1, x_2, y_2, x_3, y_3, x_4, y_4 \leq 100$. Each value is a real number with at most 5 digits after the decimal point.

Output

For each dataset, print "YES" or "NO" in a line.

Example

Input

2
0.0 0.0 1.0 1.0 1.0 0.0 2.0 1.0
3.0 2.0 9.0 6.0 13.0 5.0 7.0 9.0

Output

YES
NO

```python
num=int(input())
for i in range (num):
    info=list(map(float,input().split()))
    info=list(map(lambda x:int(x*10**6),info))
    if info[2]==info[0]:
        if info[6]==info[4]:
            print("YES")
        else:
            print("NO")
    elif info[6]==info[4]:
        if info[2]==info[0]:
            print("YES")
        else:
            print("NO")
    else:
        if (info[3]-info[1])/(info[2]-info[0])==(info[7]-info[5])/(info[6]-info[4]):
            print("YES")
        else:
            print("NO")
```