834_C. The Meaningless Game

<image>

Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.

The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.

Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.

Input

In the first string, the number of games n (1 ≤ n ≤ 350000) is given.

Each game is represented by a pair of scores a, b (1 ≤ a, b ≤ 109) – the results of Slastyona and Pushok, correspondingly.

Output

For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.

You can output each letter in arbitrary case (upper or lower).

Example

Input

6
2 4
75 45
8 8
16 16
247 994
1000000000 1000000

Output

Yes
Yes
Yes
No
No
Yes

Note

First game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.

The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.

```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction

mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

# -------------------game starts now----------------------------------------------------import math
class TreeNode:
    def __init__(self, k, v):
        self.key = k
        self.value = v
        self.left = None
        self.right = None
        self.parent = None
        self.height = 1
        self.num_left = 1
        self.num_total = 1

class AvlTree:

    def __init__(self):
        self._tree = None

    def add(self, k, v):
        if not self._tree:
            self._tree = TreeNode(k, v)
            return
        node = self._add(k, v)
        if node:
            self._rebalance(node)

    def _add(self, k, v):
        node = self._tree
        while node:
            if k < node.key:
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(k, v)
                    node.left.parent = node
                    return node.left
            elif node.key < k:
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(k, v)
                    node.right.parent = node
                    return node.right
            else:
                node.value = v
                return

    @staticmethod
    def get_height(x):
        return x.height if x else 0

    @staticmethod
    def get_num_total(x):
        return x.num_total if x else 0

    def _rebalance(self, node):

        n = node
        while n:
            lh = self.get_height(n.left)
            rh = self.get_height(n.right)
            n.height = max(lh, rh) + 1
            balance_factor = lh - rh
            n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
            n.num_left = 1 + self.get_num_total(n.left)

            if balance_factor > 1:
                if self.get_height(n.left.left) < self.get_height(n.left.right):
                    self._rotate_left(n.left)
                self._rotate_right(n)
            elif balance_factor < -1:
                if self.get_height(n.right.right) < self.get_height(n.right.left):
                    self._rotate_right(n.right)
                self._rotate_left(n)
            else:
                n = n.parent

    def _remove_one(self, node):
        """
        Side effect!!! Changes node. Node should have exactly one child
        """
        replacement = node.left or node.right
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = replacement
            else:
                node.parent.right = replacement
            replacement.parent = node.parent
            node.parent = None
        else:
            self._tree = replacement
            replacement.parent = None
        node.left = None
        node.right = None
        node.parent = None
        self._rebalance(replacement)

    def _remove_leaf(self, node):
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = None
            else:
                node.parent.right = None
            self._rebalance(node.parent)
        else:
            self._tree = None
        node.parent = None
        node.left = None
        node.right = None

    def remove(self, k):
        node = self._get_node(k)
        if not node:
            return
        if AvlTree._is_leaf(node):
            self._remove_leaf(node)
            return
        if node.left and node.right:
            nxt = AvlTree._get_next(node)
            node.key = nxt.key
            node.value = nxt.value
            if self._is_leaf(nxt):
                self._remove_leaf(nxt)
            else:
                self._remove_one(nxt)
            self._rebalance(node)
        else:
            self._remove_one(node)

    def get(self, k):
        node = self._get_node(k)
        return node.value if node else -1

    def _get_node(self, k):
        if not self._tree:
            return None
        node = self._tree
        while node:
            if k < node.key:
                node = node.left
            elif node.key < k:
                node = node.right
            else:
                return node
        return None

    def get_at(self, pos):
        x = pos + 1
        node = self._tree
        while node:
            if x < node.num_left:
                node = node.left
            elif node.num_left < x:
                x -= node.num_left
                node = node.right
            else:
                return (node.key, node.value)
        raise IndexError("Out of ranges")

    @staticmethod
    def _is_left(node):
        return node.parent.left and node.parent.left == node

    @staticmethod
    def _is_leaf(node):
        return node.left is None and node.right is None

    def _rotate_right(self, node):
        if not node.parent:
            self._tree = node.left
            node.left.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.left
            node.left.parent = node.parent
        else:
            node.parent.right = node.left
            node.left.parent = node.parent
        bk = node.left.right
        node.left.right = node
        node.parent = node.left
        node.left = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    def _rotate_left(self, node):
        if not node.parent:
            self._tree = node.right
            node.right.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.right
            node.right.parent = node.parent
        else:
            node.parent.right = node.right
            node.right.parent = node.parent
        bk = node.right.left
        node.right.left = node
        node.parent = node.right
        node.right = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    @staticmethod
    def _get_next(node):
        if not node.right:
            return node.parent
        n = node.right
        while n.left:
            n = n.left
        return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default='z', func=lambda a, b: min(a ,b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: a + b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]

class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
    if a == 1 or n == 0:
        return 1
    if n % 2 == 0:
        s = powm(a, n // 2, m)
        return s * s % m
    else:
        return a * powm(a, n - 1, m) % m

# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z

# --------------------------------------------------product----------------------------------------
def product(l):
    por = 1
    for i in range(len(l)):
        por *= l[i]
    return por

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

    count = 0

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

        # Check if middle element is
        # less than or equal to key
        if (arr[mid]<=key):
            count = mid+1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count

# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c

def countGreater( arr,n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] >= k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)

# --------------------------------------------------binary------------------------------------
for i in range(int(input())):
    a,b=map(int,input().split())
    #c=a*b
    l=int((a*b)**(1/3)+0.5)
    if l**3==a*b and a%l==0 and b%l==0:
        print("YES")
    else:
        print("NO")
```


855_A. Tom Riddle's Diary

Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.

He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.

Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes).

Input

First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list.

Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100.

Output

Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not.

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

Examples

Input

6
tom
lucius
ginny
harry
ginny
harry

Output

NO
NO
NO
NO
YES
YES

Input

3
a
a
a

Output

NO
YES
YES

Note

In test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".

```python
l = []
for _ in range(int(input())):
    s = input()
    if s not in l:
        print('NO')
        l.append(s)
    else:
        print('YES')

```


879_D. Teams Formation

This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has n passenger seats, seat i can be occupied only by a participant from the city ai.

Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence a1, a2, ..., an repeated m times).

After that some teams were formed, each consisting of k participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no k neighboring participants from the same city.

Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected.

Input

The first line contains three integers n, k and m (1 ≤ n ≤ 105, 2 ≤ k ≤ 109, 1 ≤ m ≤ 109).

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number of city, person from which must take seat i in the bus.

Output

Output the number of remaining participants in the line.

Examples

Input

4 2 5
1 2 3 1

Output

12

Input

1 9 10
1

Output

1

Input

3 2 10
1 2 1

Output

0

Note

In the second example, the line consists of ten participants from the same city. Nine of them will form a team. At the end, only one participant will stay in the line.

```python
def main():
    _, k, m = [int(x) for x in input().split()]
    a = []
    last = ("-1", 0)
    a.append(last)
    for ai in input().split():
        if last[0] == ai:
            last = (ai, last[1]+1)
            a[-1] = last
        else:
            last = (ai, 1)
            a.append(last)

        if last[1] == k:
            a.pop()
            last = a[-1]
    a.pop(0)

    s1 = 0
    while len(a) > 0 and a[0][0] == a[-1][0]:
        if len(a) == 1:
            s = a[0][1] * m
            r1 = s % k
            if r1 == 0:
                print(s1 % k)
            else:
                print(r1 + s1)
            return
        join = a[0][1] + a[-1][1]

        if join < k:
            break
        elif join % k == 0:
            s1 += join
            a.pop()
            a.pop(0)
        else:
            s1 += (join // k) * k
            a[0] = (a[0][0], join % k)
            a.pop()
            break

    s = 0
    for ai in a:
        s += ai[1]

    print(s*m + s1)

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


903_A. Hungry Student Problem

Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.

CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly this amount of chicken.

Formally, Ivan wants to know if he can choose two non-negative integers a and b in such a way that a small portions and b large ones contain exactly x chunks.

Help Ivan to answer this question for several values of x!

Input

The first line contains one integer n (1 ≤ n ≤ 100) — the number of testcases.

The i-th of the following n lines contains one integer xi (1 ≤ xi ≤ 100) — the number of chicken chunks Ivan wants to eat.

Output

Print n lines, in i-th line output YES if Ivan can buy exactly xi chunks. Otherwise, print NO.

Example

Input

2
6
5

Output

YES
NO

Note

In the first example Ivan can buy two small portions.

In the second example Ivan cannot buy exactly 5 chunks, since one small portion is not enough, but two small portions or one large is too much.

```python
t = int(input())
for i in range(0,t):
    flag = 0
    x = int(input())
    b = 0
    temp = x
    while temp >= 0 :
        if(temp%3 == 0):
            flag = 1
            break
        b = b+1
        temp = x-7*b

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

```


925_B. Resource Distribution

One department of some software company has n servers of different specifications. Servers are indexed with consecutive integers from 1 to n. Suppose that the specifications of the j-th server may be expressed with a single integer number c_j of artificial resource units.

In order for production to work, it is needed to deploy two services S_1 and S_2 to process incoming requests using the servers of the department. Processing of incoming requests of service S_i takes x_i resource units.

The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service S_i is deployed using k_i servers, then the load is divided equally between these servers and each server requires only x_i / k_i (that may be a fractional number) resource units.

Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.

Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services.

Input

The first line contains three integers n, x_1, x_2 (2 ≤ n ≤ 300 000, 1 ≤ x_1, x_2 ≤ 10^9) — the number of servers that the department may use, and resource units requirements for each of the services.

The second line contains n space-separated integers c_1, c_2, …, c_n (1 ≤ c_i ≤ 10^9) — the number of resource units provided by each of the servers.

Output

If it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes).

Otherwise print the word "Yes" (without the quotes).

In the second line print two integers k_1 and k_2 (1 ≤ k_1, k_2 ≤ n) — the number of servers used for each of the services.

In the third line print k_1 integers, the indices of the servers that will be used for the first service.

In the fourth line print k_2 integers, the indices of the servers that will be used for the second service.

No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them.

Examples

Input

6 8 16
3 5 2 9 8 7

Output

Yes
3 2
1 2 6
5 4

Input

4 20 32
21 11 11 12

Output

Yes
1 3
1
2 3 4

Input

4 11 32
5 5 16 16

Output

No

Input

5 12 20
7 8 4 11 9

Output

No

Note

In the first sample test each of the servers 1, 2 and 6 will will provide 8 / 3 = 2.(6) resource units and each of the servers 5, 4 will provide 16 / 2 = 8 resource units.

In the second sample test the first server will provide 20 resource units and each of the remaining servers will provide 32 / 3 = 10.(6) resource units.

```python
def fin(c, x):
    return (x + c - 1) // c

def ck(x, b):
    r = (n, n)
    for i in range(b, n):
        r = min(r, (i + fin(c[i][0], x), i))
    return r

def sol(r, l):
    if r[0] <= n and l[0] <= n and r[1] < n and l[1] < n :
        print("Yes")
        print(r[0] - r[1], l[0]- l[1])
        print(' '.join([str(x[1]) for x in c[r[1]:r[0]]]))
        print(' '.join([str(x[1]) for x in c[l[1]:l[0]]]))
        return True
    else:
        return False

n, x1, x2 = [int(x) for x in input().split()]
c = sorted([(int(x), i + 1) for i, x in enumerate(input().split())])

r1 = ck(x1, 0)
l1 = ck(x2, r1[0])
r2 = ck(x2, 0)
l2 = ck(x1, r2[0])

if not sol(r1, l1) and not sol(l2, r2):
    print("No")
#          6 8 16
#          3 5 2 9 8 7
```


954_C. Matrix Walk

There is a matrix A of size x × y filled with integers. For every <image>, <image> Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix.

You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.

From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells:

  1. (i + 1, j) — only if i < x;
  2. (i, j + 1) — only if j < y;
  3. (i - 1, j) — only if i > 1;
  4. (i, j - 1) — only if j > 1.

Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?

Input

The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice).

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.

Output

If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO.

Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.

Examples

Input

8
1 2 3 6 9 8 5 2

Output

YES
3 3

Input

6
1 2 1 2 5 3

Output

NO

Input

2
1 10

Output

YES
4 9

Note

The matrix and the path on it in the first test looks like this:

<image>

Also there exist multiple correct answers for both the first and the third examples.

```python
def main():
    int(input())
    a = list(map(int, input().split()))

    ds = [i - j for i, j in zip(a[1:], a)]
    dss = set(abs(x) for x in ds)
    if 0 in dss:
        return False
    try:
        dss.remove(1)
    except KeyError:
        pass
    if len(dss) > 1:
        return False
    if not dss:
        return 1e9, 1e9

    y = next(iter(dss))
    for d, c in zip(ds, a):
        j = (c - 1) % y
        if d == 1 and j == y - 1:
            return False
        if d == -1 and j == 0:
            return False
    return 1e9, y

ans = main()
if ans:
    print('YES')
    print('%d %d' % ans)
else:
    print('NO')

```


980_B. Marlin

The city of Fishtopia can be imagined as a grid of 4 rows and an odd number of columns. It has two main villages; the first is located at the top-left cell (1,1), people who stay there love fishing at the Tuna pond at the bottom-right cell (4, n). The second village is located at (4, 1) and its people love the Salmon pond at (1, n).

The mayor of Fishtopia wants to place k hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.

A person can move from one cell to another if those cells are not occupied by hotels and share a side.

Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond?

Input

The first line of input contain two integers, n and k (3 ≤ n ≤ 99, 0 ≤ k ≤ 2×(n-2)), n is odd, the width of the city, and the number of hotels to be placed, respectively.

Output

Print "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO".

If it is possible, print an extra 4 lines that describe the city, each line should have n characters, each of which is "#" if that cell has a hotel on it, or "." if not.

Examples

Input

7 2

Output

YES
.......
.#.....
.#.....
.......

Input

5 3

Output

YES
.....
.###.
.....
.....

```python
EMPTY = "."
HOTEL = "#"

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

    print("YES")

    print(EMPTY * n)

    if k % 2 == 0:
        m = k // 2
        s = EMPTY + HOTEL * m + EMPTY * (n - m - 1)
        print(s)
        print(s)
    elif k < n - 1:
        s = (HOTEL * k).center(n, EMPTY)
        print(s)
        print(EMPTY * n)
    else:
        print(EMPTY + HOTEL * (n - 2) + EMPTY)
        print(EMPTY + HOTEL * (k - n + 1) + EMPTY * (2 * n - k - 4) + HOTEL + EMPTY)

    print(EMPTY * n)

main()

```


9_B. Running Student

And again a misfortune fell on Poor Student. He is being late for an exam.

Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.

Poor Student knows the following:

  * during one run the minibus makes n stops, the i-th stop is in point (xi, 0)
  * coordinates of all the stops are different
  * the minibus drives at a constant speed, equal to vb
  * it can be assumed the passengers get on and off the minibus at a bus stop momentarily
  * Student can get off the minibus only at a bus stop
  * Student will have to get off the minibus at a terminal stop, if he does not get off earlier
  * the University, where the exam will be held, is in point (xu, yu)
  * Student can run from a bus stop to the University at a constant speed vs as long as needed
  * a distance between two points can be calculated according to the following formula: <image>
  * Student is already on the minibus, so, he cannot get off at the first bus stop

Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

Input

The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.

Output

In the only line output the answer to the problem — index of the optimum bus stop.

Examples

Input

4 5 2
0 2 4 6
4 1

Output

3

Input

2 1 1
0 100000
100000 100000

Output

2

Note

As you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.


p02545 ACL Contest 1 - Center Rearranging

Given are integer sequences A and B of length 3N. Each of these two sequences contains three copies of each of 1, 2, \dots, N. In other words, A and B are both arrangements of (1, 1, 1, 2, 2, 2, \dots, N, N, N).

Tak can perform the following operation to the sequence A arbitrarily many times:

* Pick a value from 1, 2, \dots, N and call it x. A contains exactly three copies of x. Remove the middle element of these three. After that, append x to the beginning or the end of A.

Check if he can turn A into B. If he can, print the minimum required number of operations to achieve that.

Constraints

* 1 \leq N \leq 33
* A and B are both arrangements of (1, 1, 1, 2, 2, 2, \dots, N, N, N).
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{3N}
B_1 B_2 ... B_{3N}

Output

If Tak can turn A into B, print the minimum required number of operations to achieve that. Otherwise, print -1.

Examples

Input

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

Output

4

Input

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

Output

0

Input

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

Output

-1

Input

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

Output

7

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

class E:
	def __init__(self,to,nx):
		self.to=to
		self.nx=nx

class Graph:
	def __init__(self,n):
		self.n=n
		self.head=[None]*n

	def ae(self,a,b):
		head=self.head
		head[a]=E(b,head[a])
		#head[b]=E(a,head[b])
		return head[a]

def scc(g):
	n=g.n
	cur=g.head
	last=[None]*n
	order=[-1]*n
	low=[-1]*n
	bl=[-1]*n
	idx=[]
	st=[]
	num=0
	for i in range(n):
		if order[i]!=-1:
			continue
		rec=[i]
		while rec:
			v=rec[-1]
			if last[v] is None:
				#first in v

				order[v]=low[v]=num
				num+=1
				st.append(v)
			else:
				#process last edge

				low[v]=min(low[v],low[last[v].to])

			found=False
			while cur[v] is not None:
				#process next edge
				e=cur[v]
				cur[v]=e.nx
				to=e.to

				if order[to]==-1:
					#visit another node
					rec.append(to)
					last[v]=e
					found=True
					break
				elif bl[to]==-1:
					low[v]=min(low[v],order[to])

			if not found:
				#last out v
				rec.pop()

				if order[v]==low[v]:
					c=len(idx)
					tmp=[]
					while True:
						a=st.pop()
						bl[a]=c
						tmp.append(a)
						if v==a:
							break
					idx.append(tmp)

	s=len(idx)
	for i in range(n):
		bl[i]=s-1-bl[i]
	idx.reverse()

	return (s,bl,idx)

class twosat:
	def __init__(self,n):
		self.n=n
		self.g=Graph(2*n)

	def add(self,x,y):
		self.g.ae(x^1,y)
		self.g.ae(y^1,x)

	def solve(self):
		s,bl,idx=scc(self.g)
		for i in range(self.n):
			if bl[i*2]==bl[i*2+1]:
				return False
		return True

n=int(readline())
N=n*3
a=list(map(int,readline().split()))
b=list(map(int,readline().split()))

for i in range(N):
	a[i]-=1
	b[i]-=1

apos=[[] for i in range(n)]
for i in range(N):
	apos[a[i]].append(i)

bpos=[[] for i in range(n)]
for i in range(N):
	bpos[b[i]].append(i)

def feasible(l,r):
	t=[False]*N

	def issubseq():
		head=l
		for i in range(N):
			if t[i]:
				while head<r and a[i]!=b[head]:
					head+=1
				if head==r:
					return False
				head+=1
		return True

	l2r=[]
	r2l=[]
	w=[]
	for val in range(n):
		z=[]
		for x in bpos[val]:
			if x<l:
				z.append(0)
			elif x<r:
				z.append(1)
			else:
				z.append(2)

		if z==[0,0,0]:
			return False
		elif z==[0,0,1]:
			t[apos[val][2]]=1
		elif z==[0,0,2]:
			x=l-bpos[val][0]
			y=bpos[val][2]-r
			r2l.append((x,y))
		elif z==[0,1,1]:
			t[apos[val][0]]=1
			t[apos[val][2]]=1
		elif z==[0,1,2]:
			x=l-bpos[val][0]
			y=bpos[val][2]-r
			w.append((apos[val][0],apos[val][2],x,y))
		elif z==[0,2,2]:
			x=l-bpos[val][0]
			y=bpos[val][2]-r
			l2r.append((x,y))
		elif z==[1,1,1]:
			t[apos[val][0]]=1
			t[apos[val][1]]=1
			t[apos[val][2]]=1
		elif z==[1,1,2]:
			t[apos[val][0]]=1
			t[apos[val][2]]=1
		elif z==[1,2,2]:
			t[apos[val][0]]=1
		elif z==[2,2,2]:
			return False
		else:
			assert False

	if not issubseq():
		return False

	def conflict(xa,xb,ya,yb):
		return ya<=xa and xb<=yb

	for xa,xb in l2r:
		for ya,yb in r2l:
			if conflict(xa,xb,ya,yb):
				return False

	s=len(w)
	ts=twosat(s)

	for i in range(s):
		pa,pb,qa,qb=w[i]

		#left is ok?
		ok=True
		t[pa]=1
		if not issubseq():
			ok=False
		t[pa]=0;
		if ok:
			for xa,xb in l2r:
				if conflict(xa,xb,qa,qb):
					ok=False
		if not ok:
			ts.add(i*2+1,i*2+1)

		#right is ok?
		ok=True
		t[pb]=1;
		if not issubseq():
			ok=False
		t[pb]=0;
		if ok:
			for ya,yb in r2l:
				if conflict(qa,qb,ya,yb):
					ok=False
		if not ok:
			ts.add(i*2,i*2)

	for i in range(s):
		for j in range(i+1,s):
			p0a,p0b,q0a,q0b=w[i]
			p1a,p1b,q1a,q1b=w[j]
			t0=bpos[a[p0a]][1]
			t1=bpos[a[p1a]][1]

			#left-left is ok?
			ok=True
			if (p0a<p1a)!=(t0<t1):
				ok=False
			if not ok:
				ts.add(i*2+1,j*2+1)

			#left-right is ok?
			ok=True
			if (p0a<p1b)!=(t0<t1):
				ok=False
			if conflict(q1a,q1b,q0a,q0b):
				ok=False
			if not ok:
				ts.add(i*2+1,j*2)

			#right-left is ok?
			ok=True
			if (p0b<p1a)!=(t0<t1):
				ok=False;
			if conflict(q0a,q0b,q1a,q1b):
				ok=False
			if not ok:
				ts.add(i*2,j*2+1)

			#right-right is ok?
			ok=True
			if (p0b<p1b)!=(t0<t1):
				ok=False
			if not ok:
				ts.add(i*2,j*2);

	return ts.solve();

ans=10**18
for i in range(N):
	for j in range(i,N+1):
		if feasible(i,j):
			ans=min(ans,N-(j-i))

if ans==10**18:
	ans=-1

print(ans)

```


p02676 AtCoder Beginner Contest 168 - ... (Triple Dots)

We have a string S consisting of lowercase English letters.

If the length of S is at most K, print S without change.

If the length of S exceeds K, extract the first K characters in S, append `...` to the end of them, and print the result.

Constraints

* K is an integer between 1 and 100 (inclusive).
* S is a string consisting of lowercase English letters.
* The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

K
S

Output

Print a string as stated in Problem Statement.

Examples

Input

7
nikoandsolstice

Output

nikoand...

Input

40
ferelibenterhominesidquodvoluntcredunt

Output

ferelibenterhominesidquodvoluntcredunt

```python
K = int(input())
S = input()

print(S[:K] + "...") if len(S) > K else print(S)

```


p02804 AtCoder Beginner Contest 151 - Max-Min Sums

For a finite set of integers X, let f(X)=\max X - \min X.

Given are N integers A_1,...,A_N.

We will choose K of them and let S be the set of the integers chosen. If we distinguish elements with different indices even when their values are the same, there are {}_N C_K ways to make this choice. Find the sum of f(S) over all those ways.

Since the answer can be enormous, print it \bmod (10^9+7).

Constraints

* 1 \leq N \leq 10^5
* 1 \leq K \leq N
* |A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 ... A_N

Output

Print the answer \bmod (10^9+7).

Examples

Input

4 2
1 1 3 4

Output

11

Input

6 3
10 10 10 -10 -10 -10

Output

360

Input

3 1
1 1 1

Output

0

Input

10 6
1000000000 1000000000 1000000000 1000000000 1000000000 0 0 0 0 0

Output

999998537

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

mod = 10**9+7

A = sorted(A)

bikkuri = [1]
for i in range(1,N+1):
    bikkuri.append((bikkuri[-1]*i)%mod)
bikkuri2 = [1]
for i in range(1,N+1):
    bikkuri2.append(pow(bikkuri[i],mod-2,mod))

def comb(n,r):
    if n<r:
        return 0
    else:
        return (bikkuri[n]*bikkuri2[n-r]*bikkuri2[r])%mod

ans = 0
for i in range(N):
    ans += A[i]*(comb(i,K-1)-comb(N-i-1,K-1))
    ans %= mod
print(ans)
```


p02940 AtCoder Grand Contest 037 - RGB Balls

We have 3N colored balls with IDs from 1 to 3N. A string S of length 3N represents the colors of the balls. The color of Ball i is red if S_i is `R`, green if S_i is `G`, and blue if S_i is `B`. There are N red balls, N green balls, and N blue balls.

Takahashi will distribute these 3N balls to N people so that each person gets one red ball, one blue ball, and one green ball. The people want balls with IDs close to each other, so he will additionally satisfy the following condition:

* Let a_j < b_j < c_j be the IDs of the balls received by the j-th person in ascending order.
* Then, \sum_j (c_j-a_j) should be as small as possible.

Find the number of ways in which Takahashi can distribute the balls. Since the answer can be enormous, compute it modulo 998244353. We consider two ways to distribute the balls different if and only if there is a person who receives different sets of balls.

Constraints

* 1 \leq N \leq 10^5
* |S|=3N
* S consists of `R`, `G`, and `B`, and each of these characters occurs N times in S.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of ways in which Takahashi can distribute the balls, modulo 998244353.

Examples

Input

3
RRRGGGBBB

Output

216

Input

5
BBRGRRGRGGRBBGB

Output

960

```python
MOD = 998244353

N = int(input())
Ss = input()

convs = {'R': 0, 'G': 1, 'B': 2}
num0 = N
num1s = [0] * 3
num2s = [0] * 3
ans = 1
for S in Ss:
    c = convs[S]
    if num2s[c]:
        ans *= num2s[c]
        num2s[c] -= 1
    else:
        for i in range(3):
            if i == c: continue
            if num1s[i]:
                ans *= num1s[i]
                num1s[i] -= 1
                num2s[3-i-c] += 1
                break
        else:
            ans *= num0
            num0 -= 1
            num1s[c] += 1
    ans %= MOD

print(ans)

```


p03077 AtCoder Beginner Contest 123 - Five Transportations

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

* Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.
* Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.
* Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.
* Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.
* Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.
At least how long does it take for all of them to reach there? You can ignore the time needed to transfer.

Constraints

* 1 \leq N, A, B, C, D, E \leq 10^{15}
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Examples

Input

5
3
2
4
3
5

Output

7

Input

10
123
123
123
123
123

Output

5

Input

10000000007
2
3
5
7
11

Output

5000000008

```python
n = int(input())
l = [int(input()) for _ in range(5)]
print(-(-n//min(l))+4)
```


p03219 AtCoder Beginner Contest 113 - Discount Fare

There is a train going from Station A to Station B that costs X yen (the currency of Japan).

Also, there is a bus going from Station B to Station C that costs Y yen.

Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.

How much does it cost to travel from Station A to Station C if she uses this ticket?

Constraints

* 1 \leq X,Y \leq 100
* Y is an even number.
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If it costs x yen to travel from Station A to Station C, print x.

Examples

Input

81 58

Output

110

Input

4 54

Output

31

```python
L = list(map(int,input().split()))

print(L[0]+L[1]//2)
```


p03691 AtCoder Grand Contest 016 - Poor Turkeys

There are N turkeys. We number them from 1 through N.

M men will visit here one by one. The i-th man to visit will take the following action:

* If both turkeys x_i and y_i are alive: selects one of them with equal probability, then eats it.
* If either turkey x_i or y_i is alive (but not both): eats the alive one.
* If neither turkey x_i nor y_i is alive: does nothing.

Find the number of pairs (i,\ j) (1 ≤ i < j ≤ N) such that the following condition is held:

* The probability of both turkeys i and j being alive after all the men took actions, is greater than 0.

Constraints

* 2 ≤ N ≤ 400
* 1 ≤ M ≤ 10^5
* 1 ≤ x_i < y_i ≤ N

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the number of pairs (i,\ j) (1 ≤ i < j ≤ N) such that the condition is held.

Examples

Input

3 1
1 2

Output

2

Input

4 3
1 2
3 4
2 3

Output

1

Input

3 2
1 2
1 2

Output

0

Input

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

Output

5

```python
import sys

from itertools import combinations

def solve(n, pairs):
    survivors = {v: {v} for v in range(1, n + 1)}
    for x, y in reversed(pairs):
        for v, srv in survivors.copy().items():
            if x in srv:
                if y in srv:
                    del survivors[v]
                else:
                    srv.add(y)
            elif y in srv:
                srv.add(x)
    return sum(su.isdisjoint(sv) for su, sv in combinations(survivors.values(), 2))

n, m = map(int, input().split())
pairs = [tuple(map(int, line.split())) for line in sys.stdin.readlines()]
print(solve(n, pairs))

```


p03844 AtCoder Beginner Contest 050 - Addition and Subtraction Easy

Joisino wants to evaluate the formula "A op B". Here, A and B are integers, and the binary operator op is either `+` or `-`. Your task is to evaluate the formula instead of her.

Constraints

* 1≦A,B≦10^9
* op is either `+` or `-`.

Input

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

A op B

Output

Evaluate the formula and print the result.

Examples

Input

1 + 2

Output

3

Input

5 - 7

Output

-2

```python
a,b,c=input().split();print(int(a)+int(c)if b=='+'else int(a)-int(c))
```


p04011 AtCoder Beginner Contest 044 - Tak and Hotels (ABC Edit)

There is a hotel with the following accommodation fee:

* X yen (the currency of Japan) per night, for the first K nights
* Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights. Find his total accommodation fee.

Constraints

* 1 \leq N, K \leq 10000
* 1 \leq Y < X \leq 10000
* N,\,K,\,X,\,Y are integers.

Input

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

N
K
X
Y

Output

Print Tak's total accommodation fee.

Examples

Input

5
3
10000
9000

Output

48000

Input

2
3
10000
9000

Output

20000

```python
a,b,c,d=[int(input()) for i in range(4)]
if a<=b:
  print(a*c)
else:
  print(b*c+(a-b)*d)

```


p00097 Sum of Integers II

Write a program that extracts n different numbers from the numbers 0 to 100 and outputs the number of combinations that add up to s. Each n number is from 0 to 100, and the same number cannot be used in one combination. For example, if n is 3 and s is 6, the combination of the three numbers totaling 6 is

1 + 2 + 3 = 6
0 + 1 + 5 = 6
0 + 2 + 4 = 6

There are three ways.

Input

Given multiple datasets. For each dataset, n (1 ≤ n ≤ 9) and s (0 ≤ s ≤ 1000) are given on one line, separated by a space. When both n and s are 0, it is the end of the input.

The number of datasets does not exceed 50.

Output

For each dataset, output the number of combinations in which the sum of n integers is s on one line.

No input is given with more than 1010 combinations.

Example

Input

3 6
3 1
0 0

Output

3
0

```python
dp = [[0 for _ in range(1001)] for _ in range(10)]
dp[1][0] = dp[0][0] = 1

for now in range(1, 101):
  for used in range(9, 0, -1):
    dpu = dp[used]
    dpu_1 = dp[used - 1]
    for s in range(now, 1001):
      dpu[s] = dpu_1[s - now] + dpu[s]

while True:
  n, s = map(int, input().split())
  if not n:
    break
  print(dp[n][s])

```


p00229 Big Hit !

Ataru Oafoot of Aizu Gakuen University High School decided to play with a slot machine.

When you insert a medal on this machine, three reels will start spinning and each reel will stop automatically. In a normal game (normal game), 3 medals are inserted, and when the symbols are aligned, the following medals are obtained according to the symbols.

<image>

A special service will be started depending on how the patterns are aligned. A big bonus starts when you have 3 of 7 symbols, and you can play 5 bonus games. Also, when you have 3 BAR symbols, the regular bonus will start and you can play 3 bonus games.

If you have 3 star symbols, the free game will start and you will not be able to get medals, but you can start the next game without inserting medals.

During the bonus game, if you insert 2 medals per game, you will automatically get 3 grape patterns and 15 medals.

Oafoot started playing on the machine with 100 medals. After playing for a while, it ended in a normal game. How many medals did you have left?

Create a program that inputs play information and outputs the number of medals left at hand. The play information is given as the number of big bonuses b, the number of regular bonuses r, the number of grapes aligned during a normal game g, the number of cherries aligned c, the number of stars aligned s, and the total number of games t.

Note that t includes the number of bonus games. Also, medals will not disappear in the middle of the game.

Input

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

b r g c s t

b, r, g, c, and s are integers greater than or equal to 0 and less than 200, and t is an integer less than or equal to 1000.

The number of datasets does not exceed 120.

Output

For each input dataset, the number of medals remaining at hand is output on one line.

Example

Input

3 2 30 3 26 226
9 0 18 3 20 118
5 5 12 2 15 203
7 4 19 2 22 197
7 4 24 4 17 209
0 0 0 0 0 0

Output

127
793
414
629
617


p00391 Treasure Map

Mr. Kobou found a bundle of old paper when he was cleaning his family home. On each paper, two series of numbers are written. Strange as it appeared to him, Mr. Kobou further went through the storehouse and found out a note his ancestor left. According to it, the bundle of paper is a treasure map, in which the two sequences of numbers seem to give a clue to the whereabouts of the treasure the ancestor buried.

Mr. Kobou’s ancestor divided the area where he buried his treasure in a reticular pattern and used only some of the grid sections. The two series of numbers indicate the locations: the $i$-th member of the first series indicates the number of locations in the $i$-th column (form left) of the grid sections where a part of the treasure is buried, and the $j$-th member of the second indicates the same information regarding the $j$-th row from the top. No more than one piece of treasure is buried in one grid section. An example of a 5 × 4 case is shown below. If the pieces of treasure are buried in the grid sections noted as "#" the two series of numbers become "0,2,2,1,1" and "1,1,1,3".

| 0| 2| 2| 1| 1
---|---|---|---|---|---
1|  |  | #|  |
1|  | #|  |  |
1|  |  |  |  | #
3|  | #| #| #|

Mr. Kobou’s ancestor seems to be a very careful person. He slipped some pieces of paper with completely irrelevant information into the bundle. For example, a set of number series "3,2,3,0,0" and "4,2,0,0,2" does not match any combination of 5 × 5 matrixes. So, Mr. Kobou has first to exclude these pieces of garbage information.

Given the set of information written on the pieces of paper, make a program to judge if the information is relevant.

Input

The input is given in the following format.

$W$ $H$
$a_1$ $a_2$ $...$ $a_W$
$b_1$ $b_2$ $...$ $b_H$

The first line provides the number of horizontal partitions $W$ ($1 \leq W \leq 1000$) and vertical partitions $H$ ($1 \leq H \leq 1000$). The second line provides the $i$-th member of the first number series $a_i$ ($0 \leq a_i \leq H$) written on the paper, and the third line the $j$-th member of the second series $b_j$ ($0 \leq b_j \leq W$).

Output

Output "1" if the information written on the paper is relevant, or "0" otherwise.

Examples

Input

5 4
0 2 2 1 1
1 1 1 3

Output

1

Input

5 5
3 2 3 0 0
4 2 0 0 2

Output

0

```python
import sys,heapq
_,a,q=[[-int(e) for e in sys.stdin.readline().split() if e!='0'] for _ in[0]*3]
heapq.heapify(q)
for e in a:
	t=[]
	for _ in [0]*-e:
		if not q:print(0);exit()
		if q[0]!=-1:heapq.heappush(t,q[0]+1)
		heapq.heappop(q)
	while t:heapq.heappush(q,t[0]);heapq.heappop(t)
print(int(not q))

```


p00607 Emacs-like Editor

Emacs is a text editor which is widely used by many programmers.

The advantage of Emacs is that we can move a cursor without arrow keys and the mice. For example, the cursor can be moved right, left, down, and up by pushing f, b, n, p with the Control Key respectively. In addition, cut-and-paste can be performed without the mouse.

Your task is to write a program which simulates key operations in the Emacs-like editor. The program should read a text and print the corresponding edited text.

The text consists of several lines and each line consists of zero or more alphabets and space characters. A line, which does not have any character, is a blank line.

The editor has a cursor which can point out a character or the end-of-line in the corresponding line. The cursor can also point out the end-of-line in a blank line.

In addition, the editor has a buffer which can hold either a string (a sequence of characters) or a linefeed.

The editor accepts the following set of commands (If the corresponding line is a blank line, the word "the first character" should be "the end-of-line"):

* a
Move the cursor to the first character of the current line.
* e
Move the cursor to the end-of-line of the current line.
* p
Move the cursor to the first character of the next upper line, if it exists.
If there is no line above the current line, move the cursor to the first character of the current line.
* n
Move the cursor to the first character of the next lower line, if it exists.
If there is no line below the current line, move the cursor to the first character of the current line.
* f
Move the cursor by one character to the right, unless the cursor points out the end-of-line.
If the cursor points out the end-of-line and there is a line below the current line, move the cursor to the first character of the next lower line. Otherwise, do nothing.
* b
Move the cursor by one character to the left, unless the cursor points out the first character.
If the cursor points out the first character and there is a line above the current line, move the cursor to the end-of-line of the next upper line. Otherwise, do nothing.
* d
If the cursor points out a character, delete the character (Characters and end-of-line next to the deleted character are shifted to the left).
If the cursor points out the end-of-line and there is a line below, the next lower line is appended to the end-of-line of the current line (Lines below the current line are shifted to the upper).
Otherwise, do nothing.
* k
If the cursor points out the end-of-line and there is a line below the current line, perform the command d mentioned above, and record a linefeed on the buffer.
If the cursor does not point out the end-of-line, cut characters between the cursor (inclusive) and the end-of-line, and record them on the buffer.  After this operation, the cursor indicates the end-of-line of the current line.
* y
If the buffer is empty, do nothing.
If the buffer is holding a linefeed, insert the linefeed at the cursor. The cursor moves to the first character of the new line.
If the buffer is holding characters, insert the characters at the cursor. The cursor moves to the character or end-of-line which is originally pointed by the cursor.

The cursor position just after reading the text is the beginning of the first line, and the initial buffer is empty.

Constraints

* The number of lines in the text given as input ≤ 10
* The number of characters in a line given as input ≤ 20
* The number of commands ≤ 300
* The maximum possible number of lines in the text during operations ≤ 100
* The maximum possible number of characters in a line during operations ≤ 1000

Input

The input consists of only one data-set which includes two parts. The first part gives a text consisting of several lines. The end of the text is indicated by a line (without quotes):

"END_OF_TEXT"

This line should not be included in the text.

Next part gives a series of commands. Each command is given in a line. The end of the commands is indicated by a character '-'.

Output

For the input text, print the text edited by the commands.

Example

Input

hyo
ni
END_OF_TEXT
f
d
f
f
k
p
p
e
y
a
k
y
y
n
y
-

Output

honihoni
honi

```python
class Editer:

    def __init__(self, text):
        # カーソルの位置
        self.row = 0 #行
        self.col = 0 #列
        # 編集中のテキスト
        self.text = [list(t) + ['\n'] for t in text]
        # バッファー
        self.buffer = []

    def row_head(self):
        return 0

    def row_tail(self):
        return len(self.text) - 1

    def col_head(self):
        return 0

    def col_tail(self):
        return len(self.text[self.row]) - 1

    def __repr__(self):
        return ''.join(''.join(t) for t in self.text)

    def command_a(self):
        # カーソルを現在の行の先頭文字に移動
        self.col = self.col_head()

    def command_e(self):
        # カーソルを現在の行の行末に移動
        self.col = self.col_tail()

    def command_p(self):
        # 上に行があれば、カーソルを上の行に
        if self.row != self.row_head() :
            self.row -= 1
        # カーソルを先頭に
        self.col = self.col_head()

    def command_n(self):
        # 下に行があれば
        if self.row != self.row_tail():
            # カーソルを下の行に移動
            self.row += 1
        # カーソルを先頭文字に移動
        self.col = self.col_head()

    def command_b(self):
        # カーソルが行末にない場合
        if self.col != self.col_head():
            # カーソルを１つ左に移動
            self.col -= 1
        # カーソルが行末にあり、上に行がある場合
        elif self.row != self.row_head():
            # カーソルを前の行の先頭に
            self.row -= 1
            self.col = self.col_tail()

    def command_f(self):
        # カーソルが行末にない場合
        if self.col != self.col_tail():
            # カーソルを１つ右に移動
            self.col += 1
        # カーソルが行末にあり、下に行がある場合
        elif self.row != self.row_tail():
            # カーソルを次の行の先頭に
            self.row += 1
            self.col = self.col_head()

    def command_d(self):
        # カーソルが行末にない場合
        if self.col != self.col_tail():
            # カーソルの文字を削除
            self.text[self.row].pop(self.col)
        # カーソルが行末を指し、下に行がある場合
        elif self.row != self.row_tail():
            # 下の行をそのままカーソルの位置に繋げ、以下の行は上にシフト
            self.text[self.row].pop(self.col_tail())
            self.text[self.row] += self.text.pop(self.row+1)

    def command_k(self):
        # カーソルが行末にない場合
        if self.col != self.col_tail():
            # カーソルが指す文字を含めた右側すべての文字を切り取りそれをバッファに記録する。
            self.buffer = self.text[self.row][self.col:-1]
            self.text[self.row] = self.text[self.row][:self.col] + ['\n']
            # カーソルは元の行の行末を指すようになる
            self.col = self.col_tail()
        # カーソルが行末にあり、下に行がある場合
        elif self.row != self.row_tail():
            # バッファに改行を記録する。
            self.buffer = ['\n']
            # 下の行をそのままカーソルの位置に繋げる。以下の行は上にシフトされる。
            self.text[self.row].pop(self.col_tail())
            self.text[self.row] += self.text.pop(self.row+1)

    def command_y(self):
        '''
        カーソルが指す文字の直前にバッファを挿入
        カーソルの位置はもともと指していた文字へ移動
        バッファの内容が改行なら
        '''
        if self.buffer != ['\n']:
            self.text[self.row][self.col:self.col] = self.buffer
            self.col += len(self.buffer)

        else:
            self.text.insert(self.row+1, self.text[self.row][self.col:])
            self.text[self.row] = self.text[self.row][:self.col] + ['\n']
            self.row += 1
            self.col = self.col_head()

def main():
    # input text
    text = []
    while True:
        str = input()
        if str == 'END_OF_TEXT': break
        text.append(str)

    editer = Editer(text)

    # input command
    while True:
        command = input()
        if   command == 'a' : editer.command_a()
        elif command == 'e' : editer.command_e()
        elif command == 'p' : editer.command_p()
        elif command == 'n' : editer.command_n()
        elif command == 'f' : editer.command_f()
        elif command == 'b' : editer.command_b()
        elif command == 'd' : editer.command_d()
        elif command == 'y' : editer.command_y()
        elif command == 'k' : editer.command_k()
        elif command == '-' : break

    print(editer, end='')

if __name__ == '__main__': main()

```


p00744 Cards

There are many blue cards and red cards on the table. For each card, an integer number greater than 1 is printed on its face. The same number may be printed on several cards.

A blue card and a red card can be paired when both of the numbers printed on them have a common divisor greater than 1. There may be more than one red card that can be paired with one blue card. Also, there may be more than one blue card that can be paired with one red card. When a blue card and a red card are chosen and paired, these two cards are removed from the whole cards on the table.

<image>
Figure E-1: Four blue cards and three red cards

For example, in Figure E-1, there are four blue cards and three red cards. Numbers 2, 6, 6 and 15 are printed on the faces of the four blue cards, and 2, 3 and 35 are printed on those of the three red cards. Here, you can make pairs of blue cards and red cards as follows. First, the blue card with number 2 on it and the red card with 2 are paired and removed. Second, one of the two blue cards with 6 and the red card with 3 are paired and removed. Finally, the blue card with 15 and the red card with 35 are paired and removed. Thus the number of removed pairs is three.

Note that the total number of the pairs depends on the way of choosing cards to be paired. The blue card with 15 and the red card with 3 might be paired and removed at the beginning. In this case, there are only one more pair that can be removed and the total number of the removed pairs is two.

Your job is to find the largest number of pairs that can be removed from the given set of cards on the table.

Input

The input is a sequence of datasets. The number of the datasets is less than or equal to 100. Each dataset is formatted as follows.

> m n
>  b1 ... bk ... bm
>  r1 ... rk ... rn
>

The integers m and n are the number of blue cards and that of red cards, respectively. You may assume 1 ≤ m ≤ 500 and 1≤ n ≤ 500. bk (1 ≤ k ≤ m) and rk (1 ≤ k ≤ n) are numbers printed on the blue cards and the red cards respectively, that are integers greater than or equal to 2 and less than 10000000 (=107). The input integers are separated by a space or a newline. Each of bm and rn is followed by a newline. There are no other characters in the dataset.

The end of the input is indicated by a line containing two zeros separated by a space.

Output

For each dataset, output a line containing an integer that indicates the maximum of the number of the pairs.

Sample Input

4 3
2 6 6 15
2 3 5
2 3
4 9
8 16 32
4 2
4 9 11 13
5 7
5 5
2 3 5 1001 1001
7 11 13 30 30
10 10
2 3 5 7 9 11 13 15 17 29
4 6 10 14 18 22 26 30 34 38
20 20
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
100 100
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
117 755 835 683 52 369 302 424 513 870
75 874 299 228 140 361 30 342 750 819
761 123 804 325 952 405 578 517 49 457
932 941 988 767 624 41 912 702 241 426
351 92 300 648 318 216 785 347 556 535
166 318 434 746 419 386 928 996 680 975
231 390 916 220 933 319 37 846 797 54
272 924 145 348 350 239 563 135 362 119
446 305 213 879 51 631 43 755 405 499
509 412 887 203 408 821 298 443 445 96
274 715 796 417 839 147 654 402 280 17
298 725 98 287 382 923 694 201 679 99
699 188 288 364 389 694 185 464 138 406
558 188 897 354 603 737 277 35 139 556
826 213 59 922 499 217 846 193 416 525
69 115 489 355 256 654 49 439 118 961
0 0

Output for the Sample Input

3
1
0
4
9
18
85

Example

Input

4 3
2 6 6 15
2 3 5
2 3
4 9
8 16 32
4 2
4 9 11 13
5 7
5 5
2 3 5 1001 1001
7 11 13 30 30
10 10
2 3 5 7 9 11 13 15 17 29
4 6 10 14 18 22 26 30 34 38
20 20
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
100 100
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
117 755 835 683 52 369 302 424 513 870
75 874 299 228 140 361 30 342 750 819
761 123 804 325 952 405 578 517 49 457
932 941 988 767 624 41 912 702 241 426
351 92 300 648 318 216 785 347 556 535
166 318 434 746 419 386 928 996 680 975
231 390 916 220 933 319 37 846 797 54
272 924 145 348 350 239 563 135 362 119
446 305 213 879 51 631 43 755 405 499
509 412 887 203 408 821 298 443 445 96
274 715 796 417 839 147 654 402 280 17
298 725 98 287 382 923 694 201 679 99
699 188 288 364 389 694 185 464 138 406
558 188 897 354 603 737 277 35 139 556
826 213 59 922 499 217 846 193 416 525
69 115 489 355 256 654 49 439 118 961
0 0

Output

3
1
0
4
9
18
85

```python
import collections
import math

class Dinic:
    """Dinic Algorithm: find max-flow
       complexity: O(EV^2)
       used in GRL6A(AOJ)
    """
    class edge:
        def __init__(self, to, cap, rev):
            self.to, self.cap, self.rev = to, cap, rev

    def __init__(self, V, E, source, sink):
        """ V: the number of vertexes
            E: adjacency list
            source: start point
            sink: goal point
        """
        self.V = V
        self.E = [[] for _ in range(V)]
        for fr in range(V):
            for to, cap in E[fr]:
                self.E[fr].append(self.edge(to, cap, len(self.E[to])))
                self.E[to].append(self.edge(fr, 0, len(self.E[fr])-1))
        self.maxflow = self.dinic(source, sink)

    def dinic(self, source, sink):
        """find max-flow"""
        INF = float('inf')
        maxflow = 0
        while True:
            self.bfs(source)
            if self.level[sink] < 0:
                return maxflow
            self.itr = [0] * self.V
            while True:
                flow = self.dfs(source, sink, INF)
                if flow > 0:
                    maxflow += flow
                else:
                    break

    def dfs(self, vertex, sink, flow):
        """find augmenting path"""
        if vertex == sink:
            return flow
        for i in range(self.itr[vertex], len(self.E[vertex])):
            self.itr[vertex] = i
            e = self.E[vertex][i]
            if e.cap > 0 and self.level[vertex] < self.level[e.to]:
                d = self.dfs(e.to, sink, min(flow, e.cap))
                if d > 0:
                    e.cap -= d
                    self.E[e.to][e.rev].cap += d
                    return d
        return 0

    def bfs(self, start):
        """find shortest path from start"""
        que = collections.deque()
        self.level = [-1] * self.V
        que.append(start)
        self.level[start] = 0

        while que:
            fr = que.popleft()
            for e in self.E[fr]:
                if e.cap > 0 and self.level[e.to] < 0:
                    self.level[e.to] = self.level[fr] + 1
                    que.append(e.to)

while True:
    M, N = map(int, input().split())
    if M == 0 and N == 0:
        break
    blue, red = [], []
    while True:
        for x in input().split():
            blue.append(int(x))
        if len(blue) == M:
            break
    while True:
        for x in input().split():
            red.append(int(x))
        if len(red) == N:
            break
    V = M + N + 2
    edge = [set() for _ in range(V)]
    for i, b in enumerate(blue):
        if b != 1:
            for j, r in enumerate(red):
                if r % b == 0:
                    edge[i].add((M+j, 1))
        for j in range(2, int(math.sqrt(b)) + 1):
            if b % j == 0:
                for k, r in enumerate(red):
                    if r % j == 0 or r % (b // j) == 0:
                        edge[i].add((M+k, 1))
    for i in range(M):
        edge[M+N].add((i, 1))
    for j in range(N):
        edge[M+j].add((M+N+1, 1))
    d = Dinic(V, edge, M+N, M+N+1)
    print(d.maxflow)
```


p00883 Infected Land

The earth is under an attack of a deadly virus. Luckily, prompt actions of the Ministry of Health against this emergency successfully confined the spread of the infection within a square grid of areas. Recently, public health specialists found an interesting pattern with regard to the transition of infected areas. At each step in time, every area in the grid changes its infection state according to infection states of its directly (horizontally, vertically, and diagonally) adjacent areas.

* An infected area continues to be infected if it has two or three adjacent infected areas.
* An uninfected area becomes infected if it has exactly three adjacent infected areas.
* An area becomes free of the virus, otherwise.

Your mission is to fight against the virus and disinfect all the areas. The Ministry of Health lets an anti-virus vehicle prototype under your command. The functionality of the vehicle is summarized as follows.

* At the beginning of each time step, you move the vehicle to one of the eight adjacent areas. The vehicle is not allowed to move to an infected area (to protect its operators from the virus). It is not allowed to stay in the same area.
* Following vehicle motion, all the areas, except for the area where the vehicle is in, change their infection states according to the transition rules described above.
Special functionality of the vehicle protects its area from virus infection even if the area is adjacent to exactly three infected areas. Unfortunately, this virus-protection capability of the vehicle does not last. Once the vehicle leaves the area, depending on the infection states of the adjacent areas, the area can be infected.
The area where the vehicle is in, which is uninfected, has the same effect to its adjacent areas as an infected area as far as the transition rules are concerned.

The following series of figures illustrate a sample scenario that successfully achieves the goal.

Initially, your vehicle denoted by @ is found at (1, 5) in a 5 × 5-grid of areas, and you see some infected areas which are denoted by #'s.

<image>

Firstly, at the beginning of time step 1, you move your vehicle diagonally to the southwest, that is, to the area (2, 4). Note that this vehicle motion was possible because this area was not infected at the start of time step 1.

Following this vehicle motion, infection state of each area changes according to the transition rules. The column "1-end" of the figure illustrates the result of such changes at the end of time step 1. Note that the area (3, 3) becomes infected because there were two adjacent infected areas and the vehicle was also in an adjacent area, three areas in total.

In time step 2, you move your vehicle to the west and position it at (2, 3).

Then infection states of other areas change. Note that even if your vehicle had exactly three infected adjacent areas (west, southwest, and south), the area that is being visited by the vehicle is not infected. The result of such changes at the end of time step 2 is as depicted in "2-end".

Finally, in time step 3, you move your vehicle to the east. After the change of the infection states, you see that all the areas have become virus free! This completely disinfected situation is the goal. In the scenario we have seen, you have successfully disinfected all the areas in three time steps by commanding the vehicle to move (1) southwest, (2) west, and (3) east.

Your mission is to find the length of the shortest sequence(s) of vehicle motion commands that can successfully disinfect all the areas.

Input

The input is a sequence of datasets. The end of the input is indicated by a line containing a single zero. Each dataset is formatted as follows.

n
a11 a12 ... a1n
a21 a22 ... a2n
...
an1 an2 ... ann

Here, n is the size of the grid. That means that the grid is comprised of n × n areas. You may assume 1 ≤ n ≤ 5. The rest of the dataset consists of n lines of n letters. Each letter aij specifies the state of the area at the beginning: '#' for infection, '.' for free of virus, and '@' for the initial location of the vehicle. The only character that can appear in a line is '#', '.', or '@'. Among n × n areas, there exists exactly one area which has '@'.

Output

For each dataset, output the minimum number of time steps that is required to disinfect all the areas. If there exists no motion command sequence that leads to complete disinfection, output -1. The output should not contain any other extra character.

Examples

Input

3
...
.@.
...
3
.##
.#.
@##
3
##.
#..
@..
5
....@
##...
#....
...#.
##.##
5
#...#
...#.
#....
...##
..@..
5
#....
.....
.....
.....
..@..
5
#..#.
#.#.#
.#.#.
....#
.#@##
5
..##.
..#..
#....
#....
.#@..
0

Output

0
10
-1
3
2
1
6
4

Input

3
...
.@.
...
3
.##
.#.
@##
3
.
..
@..
5
....@
...
....
...#.
.##
5
...#
...#.
....
...##
..@..
5
....
.....
.....
.....
..@..
5
..#.
.#.#
.#.#.
....#
.#@##
5
..##.
..#..
....
....
.#@..
0

Output

0
10
-1
3
2
1
6
4

```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write

dd0 = ((-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1))
DD = []
for k in range(6):
    ddk = []
    for y in range(k):
        for x in range(k):
            v = 0
            for dx, dy in dd0:
                nx = x + dx; ny = y + dy
                if not 0 <= nx < k or not 0 <= ny < k:
                    continue
                v |= 1 << (ny*k + nx)
            ddk.append(v)
    DD.append(ddk)
L = (1 << 16)
bc = [0]*L
for v in range(1, L):
    bc[v] = bc[v ^ (v & -v)] + 1

def solve():
    N = int(readline())
    if N == 0:
        return False
    dd = dd0
    dk = DD[N]
    state = 0
    for i in range(N):
        s = readline().strip()
        for j, c in enumerate(s):
            if c == '#':
                state |= 1 << (N*i + j)
            elif c == '@':
                sx = j; sy = i
    U = {(state, sx, sy): 0}
    que = deque([(state, sx, sy)])
    while que:
        state, x, y = key = que.popleft()
        d = U[key]
        if state == 0:
            write("%d\n" % d)
            break
        for dx, dy in dd:
            nx = x + dx; ny = y + dy
            if not 0 <= nx < N or not 0 <= ny < N:
                continue
            b = 1 << (ny*N + nx)
            if state & b:
                continue
            state ^= b
            n_state = 0
            for k in range(N*N):
                v = state & dk[k]
                if state & (1 << k):
                    if v and 2 <= bc[v // (v & -v)] <= 3:
                        n_state |= (1 << k)
                else:
                    if v and bc[v // (v & -v)] == 3:
                        n_state |= (1 << k)
            if n_state & b:
                n_state ^= b
            n_key = (n_state, nx, ny)
            if n_key not in U:
                U[n_key] = d+1
                que.append(n_key)
            state ^= b
    else:
        write("-1\n")
    return True
while solve():
    ...

```


p01285 Find the Point

We understand that reading English is a great pain to many of you. So we’ll keep this problem statememt simple. Write a program that reports the point equally distant from a set of lines given as the input. In case of no solutions or multiple solutions, your program should report as such.

Input

The input consists of multiple datasets. Each dataset is given in the following format:

n
x1,1 y1,1 x1,2 y1,2
x2,1 y2,1 x2,2 y2,2
...
xn,1 yn,1 xn,2 yn,2

n is the number of lines (1 ≤ n ≤ 100); (xi,1, yi,1) and (xi,2, yi,2) denote the different points the i-th line passes through. The lines do not coincide each other. The coordinates are all integers between -10000 and 10000.

The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed.

Output

For each dataset, print a line as follows. If there is exactly one point equally distant from all the given lines, print the x- and y-coordinates in this order with a single space between them. If there is more than one such point, just print "Many" (without quotes). If there is none, just print "None" (without quotes).

The coordinates may be printed with any number of digits after the decimal point, but should be accurate to 10-4.

Example

Input

2
-35 -35 100 100
-49 49 2000 -2000
4
0 0 0 3
0 0 3 0
0 3 3 3
3 0 3 3
4
0 3 -4 6
3 0 6 -4
2 3 6 6
-1 2 -4 6
0

Output

Many
1.5000 1.5000
1.000 1.000

```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write

EPS = 1e-9
def line_cross_point(P1, P2, Q1, Q2):
    x0, y0 = P1; x1, y1 = P2
    x2, y2 = Q1; x3, y3 = Q2

    dx0 = x1 - x0; dy0 = y1 - y0
    dx1 = x3 - x2; dy1 = y3 - y2

    s = (y0-y2)*dx1 - (x0-x2)*dy1
    sm = dx0*dy1 - dy0*dx1
    if -EPS < sm < EPS:
        return None
    return x0 + s*dx0/sm, y0 + s*dy0/sm

def bisector(P1, P2, Q1, Q2):
    x0, y0 = P1; x1, y1 = P2
    x2, y2 = Q1; x3, y3 = Q2

    dx0 = x1 - x0; dy0 = y1 - y0
    dx1 = x3 - x2; dy1 = y3 - y2

    cp = line_cross_point(P1, P2, Q1, Q2)
    if cp is None:
        return None

    cx, cy = cp

    d0 = (dx0**2 + dy0**2)**.5
    d1 = (dx1**2 + dy1**2)**.5
    return [
        ((cx, cy), (cx + (dx0*d1 + dx1*d0), cy + (dy0*d1 + dy1*d0))),
        ((cx, cy), (cx + (dx0*d1 - dx1*d0), cy + (dy0*d1 - dy1*d0))),
    ]

def line_point_dist2(p1, p2, q):
    x, y = q

    x1, y1 = p1; x2, y2 = p2
    dx = x2 - x1; dy = y2 - y1
    dd = dx**2 + dy**2
    sv = (x - x1) * dy - (y - y1) * dx
    return abs(sv / dd**.5)

def check(LS, q):
    ds = [line_point_dist2(p1, p2, q) for p1, p2 in LS]
    return all(abs(ds[0] - e) < EPS for e in ds)

def solve():
    N = int(readline())
    if N == 0:
        return False
    P = []
    for i in range(N):
        x1, y1, x2, y2 = map(int, readline().split())
        P.append(((x1, y1), (x2, y2)))
    if N <= 2:
        write("Many\n")
        return True

    s = []
    for i in range(N):
        p1, p2 = P[i]
        for j in range(i):
            q1, q2 = P[j]
            bs = bisector(p1, p2, q1, q2)
            if bs is None:
                continue
            s.append(bs)
            if len(s) > 1:
                break
        else:
            continue
        break
    if len(s) < 2:
        write("None\n")
        return True
    ans = []
    b1, b2 = s
    for p1, p2 in b1:
        for q1, q2 in b2:
            cp = line_cross_point(p1, p2, q1, q2)
            if cp is None:
                continue
            if check(P, cp):
                cx, cy = cp
                for ax, ay in ans:
                    if abs(cx - ax) < EPS and abs(cy - ay) < EPS:
                        break
                else:
                    ans.append(cp)
    if len(ans) == 0:
        write("None\n")
    elif len(ans) > 1:
        write("Many\n")
    else:
        write("%.16f %.16f\n" % ans[0])
    return True
while solve():
    ...

```


p01767 RUPC

Problem statement

A programming contest will be held in the Russian Federation. The contest has N questions and has M participants. Question i has a score a_i, and it is known that participant j's ability is b_j. For problem i and participant j, participant j can always solve problem i if a_i ≤ b_j and only then. The score of a participant through the contest is the sum of the scores of the problems that the person was able to solve. Participant j also sets a target score c_j for this contest.

Determine if each participant can score more than the target score.

input

The input is given in the following format.

N
a_ {0} a_ {1} a_ {2}… a_ {N−1}
M
b_ {0} b_ {1} b_ {2}… b_ {M−1}
c_ {0} c_ {1} c_ {2}… c_ {M−1}

Constraint

* All inputs are integers
* 1 \ ≤ N \ ≤ 300 \,000
* 1 \ ≤ M \ ≤ 300 \,000
* 0 \ ≤ a_ {i} \ ≤ 1 \, 000 \,000
* 0 \ ≤ b_ {i} \ ≤ 1 \, 000 \,000
* 0 \ ≤ c_ {i} \ ≤ ∑a_k

output

Print the answer on line M. On the i-line, output `Yes` if the participant i-1 can get more points than the target score, and` No` if not.

sample

Sample input 1

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

Sample output 1

Yes
Yes
Yes
Yes
Yes
No
No

The points obtained by each participant are as follows.

* Participant 0: 1 + 1 = 2
* Participant 1: 1 + 2 + 1 + 3 = 7
* Participant 2: 1 + 2 + 1 + 3 + 4 = 11
* Participant 3: 1 + 2 + 1 + 3 + 4 + 5 = 16
* Participant 4: 1 + 2 + 1 + 3 = 7
* Participant 5: 1 + 1 = 2
* Participants 6: 0

Sample input 2

8
1 1 2 3 3 4 6 100
Four
1 3 4 99
1 10 15 120

Sample output 2

Yes
Yes
No
No

Example

Input

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

Output

Yes
Yes
Yes
Yes
Yes
No
No

```python
import bisect
n=int(input())
a=sorted(list(map(int,input().split())))
d=[0]*(n+1)
for i in range(1,n+1):d[i]=d[i-1]+a[i-1]
m=int(input())
b,c=[list(map(int,input().split())) for _ in [0,0]]
for i in range(m):
    p=bisect.bisect_right(a,b[i])
    print(['Yes','No'][d[p]<c[i]])
```


p01901 Suntan

D: Sunburn-Suntan-

story

Aizunyan is a second-year student who belongs to the programming contest club of Wakagamatsu High School, commonly known as the Prokon club. Cute like an angel. Aizu Nyan is planning to participate in this summer festival, so I made a schedule for the band to go to listen to. I'm worried about sunburn here. All live performances are held outdoors, but Aizu Nyan has a constitution that makes it easy to get sunburned, so if you are exposed to too much ultraviolet rays outdoors for a long time, you will get sunburned immediately. I plan to avoid UV rays as much as possible by evacuating indoors while there is no live performance, but during the live performance, it will inevitably hit the sun. Therefore, Aizu Nyan thought about taking measures against ultraviolet rays by applying sunscreen.

problem

If you apply sunscreen, you can get the effect for T minutes from the time you apply it. Sunscreen can only be applied once, so I want to use it effectively. Aizu Nyan is outdoors from the start time to the end time of the live, and is indoors at other times. You'll be given a live schedule that Aizu Nyan will listen to, so find the maximum amount of time you can get the sunscreen effect while you're outdoors.

Input format

The input can be given in the following format.

T
N
s_1 t_1
...
s_N t_N

The first line is given an integer T that represents the time it takes to get the sunscreen effect. The second line is given an integer N that represents the number of live concerts Aizu Nyan listens to. The following N lines are given the integer s_i, which represents the start time of the live that Aizu Nyan listens to thi, and the integer t_i, which represents the end time, separated by spaces.

Constraint

* 1 ≤ T ≤ 10 ^ {15}
* 1 ≤ N ≤ 10 ^ 5
* 0 ≤ s_i <t_i ≤ 10 ^ {15} (1 ≤ i ≤ N)
* The start time of the (i + 1) th live is the same as or later than the end time of the i-th live. That is, t_i ≤ s_ {i + 1} (1 ≤ i <N)

output

Print one line for the maximum amount of time you can get the sunscreen effect while you're outdoors.

Input example 1

20
1
0 10

Output example 1

Ten

Input example 2

20
1
0 100

Output example 2

20

Input example 3

9
3
1 5
9 11
13 20

Output example 3

7

Input example 4

twenty five
Five
9 12
15 20
21 25
28 40
45 60

Output example 4

twenty one

Example

Input

20
1
0 10

Output

10

```python
# AOJ 2801: Suntan
# Python3 2018.7.11 bal4u

from bisect import bisect_left

T, N = int(input()), int(input())
a, s, t = [0], [0], [0]
for i in range(N):
	_s, _t = map(int, input().split())
	s.append(_s)
	t.append(_t)
	a.append(a[-1]+_t-_s)
s.append(1<<62)
t.append(1<<62)
ans = 0
k = bisect_left(t, T, 0)-1
for i in range(1, N+1):
	x = s[i]+T
	k = bisect_left(t, x, k)-1
	y = a[k]-a[i-1]
	if x > s[k+1]: y += x-s[k+1]
	if y > ans:
		ans = y;
		if ans == T: break
print(ans)

```


p02038 Tanuki and Fox

problem

There is a mysterious device $ M $, and if you put Tanuki and Fox in this device, one animal will come out from the device (hereinafter, Tanuki will be $ T $ and Fox will be $ F $).

$ M (x, y) $ represents an animal that came out by putting animals in the device $ M $ in the order of $ x, y $.

As a result of various trials, the following was found.

$ M (T, T) = T $
$ M (T, F) = F $
$ M (F, T) = T $
$ M (F, F) = T $

You put the animals in a row $ P_1, P_2, ..., P_N $ into the device as follows.
$ M (.... M (M (P_1, P_2), P_3) ...., P_N) $

Answer the last animal that appears.

output

Output the last animal character $ T $ or $ F $, and also a newline at the end.

Example

Input

3
F T T

Output

T

```python
from functools import reduce

def M(x, y):
    if x == 'T' and y == 'T':
        return 'T'
    elif x == 'T' and y == 'F':
        return 'F'
    elif x == 'F' and y == 'T':
        return 'T'
    else:
        return 'T'

_ = input()
P = input().split()

print(reduce(M, P))

```


p02182 Spot The Difference

A: Find the difference

problem

Given rectangular boards A and B with N squares vertically and M squares horizontally. For each board, each square is painted white or black.

The color of the square in the i-th row and j-th column of the board X is written as C (i, j, X).

Count how many pairs of integers (i, j) meet the following conditions:

* 1 \ leq i \ leq N
* 1 \ leq j \ leq M
* C (i, j, A) \ neq C (i, j, B)

Input format

N M
A_1_1
...
A_N
B_1_1
...
B_N

When the jth character of A_i (1 \ leq i \ leq N) is `#`, C (i, j, A) is black, and when it is `.`, C (i, j, A) is white. Represents that. The same is true for B.

Constraint

* 1 \ leq N, M \ leq 2,000
* | A_i | = | B_i | = M
* A_i and B_i are strings consisting only of `#` and `.`

Output format

Print the answer on one line.

Input example 1

twenty three
.. #
..
.##
..

Output example 1

2

Input example 2

7 28
............................
... # ..... ### ... #### .... ### ..
.. #. # ... # ... # ... # ... # .... # ... #.
. # ... # ... # ...... #### ... # .....
. ##### .. # ... # .. # ...... # ... #.
. # ... # ... ### ... # ....... ### ..
............................
............................
.. ### .... ### ..... ## .... ### ..
. # ... # ... # ... # ... #. # ... # ... #.
...##...#...# ..... # .... ####.
.. # ..... # ... # ..... # ....... #.
. ##### ... ### .... #### ... ### ..
............................

Output example 2

40

Example

Input

2 3
..#
##.
.##
#..

Output

2

```python
N, M = map(int, input().split())

table1 = ''
table2 = ''

for i in range(2 * N):
    if i < N:
        table1 += input()
    else:
        table2 += input()

count = 0
for i, j in zip(table1, table2):
    if i != j:
        count+=1
print(count)

```


p02324 Chinese Postman Problem

For a given weighted undirected graph G(V, E), find the distance of the shortest route that meets the following criteria:

* It is a closed cycle where it ends at the same point it starts.
* The route must go through every edge at least once.

Constraints

* 2 ≤ |V| ≤ 15
* 0 ≤ |E| ≤ 1,000
* 0 ≤ di ≤ 1,000
* si ≠ ti
* The graph is connected

Input

|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target verticess of i-th edge (undirected) and di represents the distance between si and ti (the i-th edge).

Note that there can be multiple edges between a pair of vertices.

Output

Print the shortest distance in a line.

Examples

Input

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

Output

10

Input

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

Output

18

Input

2 3
0 1 1
0 1 2
0 1 3

Output

7

```python
import sys

f_i = sys.stdin

V, E = map(int, f_i.readline().split())

# adjacency matrix
no_edge = float("inf")

adj = [[no_edge] * V for i in range(V)]

for i in range(V):
    adj[i][i] = 0

odd_b = 0 # bit DP to record odd vertex

ans = 0

# acceptance of input
for l_i in f_i:
    s, t, d = map(int, l_i.split())
    t_d = min(d, adj[s][t])
    adj[s][t] = t_d
    adj[t][s] = t_d
    odd_b ^= 1 << s
    odd_b ^= 1 << t
    ans += d

if odd_b:
    # Warshall???Floyd Algorithm
    for k in range(V):
        for i in range(V):
            for j in range(V):
                adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j])

    # Minimum weighted matching
    mw = [no_edge] * (odd_b + 1)
    mw[0] = 0
    digits = len(bin(odd_b)) - 2

    for b in range(odd_b):
        for i in range(0, digits):
            if not (b & (1 << i)) and odd_b & (1 << i):
                for j in range(i + 1, digits):
                    if not (b & (1 << j)) and odd_b & (1 << j):
                        t_b = b + (1 << i) + (1 << j)
                        if t_b == t_b & odd_b:
                            t_w = mw[t_b]
                            mw[t_b] = min(t_w, mw[b] + adj[i][j])

    # Output
    ans += mw[odd_b]
    print(ans)
else:
    print(ans)
```


p02469 Least Common Multiple

Find the least common multiple (LCM) of given n integers.

Constraints

* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1

Input

n
a1 a2 ... an

n is given in the first line. Then, n integers are given in the second line.

Output

Print the least common multiple of the given integers in a line.

Examples

Input

3
3 4 6

Output

12

Input

4
1 2 3 5

Output

30

```python
from functools import reduce
import math

n = int(input())

def lcm_base(x, y):
    return (x * y) // math.gcd(x, y)
def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)

numlis = [int(a) for a in input().split()]
print(lcm_list(numlis))

```


1033_C. Permutation Game

After a long day, Alice and Bob decided to play a little game. The game board consists of n cells in a straight line, numbered from 1 to n, where each cell contains a number a_i between 1 and n. Furthermore, no two cells contain the same number.

A token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell i to cell j only if the following two conditions are satisfied:

  * the number in the new cell j must be strictly larger than the number in the old cell i (i.e. a_j > a_i), and
  * the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. |i-j|mod a_i = 0).

Whoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players.

Input

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

The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n). Furthermore, there are no pair of indices i ≠ j such that a_i = a_j.

Output

Print s — a string of n characters, where the i-th character represents the outcome of the game if the token is initially placed in the cell i. If Alice wins, then s_i has to be equal to "A"; otherwise, s_i has to be equal to "B".

Examples

Input

8
3 6 5 4 2 7 1 8

Output

BAAAABAB

Input

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

Output

ABAAAABBBAABAAB

Note

In the first sample, if Bob puts the token on the number (not position):

  * 1: Alice can move to any number. She can win by picking 7, from which Bob has no move.
  * 2: Alice can move to 3 and 5. Upon moving to 5, Bob can win by moving to 8. If she chooses 3 instead, she wins, as Bob has only a move to 4, from which Alice can move to 8.
  * 3: Alice can only move to 4, after which Bob wins by moving to 8.
  * 4, 5, or 6: Alice wins by moving to 8.
  * 7, 8: Alice has no move, and hence she loses immediately.

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

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

# ------------------------------

from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush

def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 1000000007
INF = float('inf')

# ------------------------------

def main():
    n = N()
    arr = RLL()
    dic = {v: i for i, v in enumerate(arr)}
    dp = [1]*n

    for i in range(n-1, 0, -1):
        for p in range(dic[i]%i, n, i):
            if arr[p]>i and dp[dic[arr[p]]]==1:
                dp[dic[i]] = 0
                break
    print("".join(['B' if i == 1 else 'A' for i in dp]))

if __name__ == "__main__":
    main()

```


1056_A. Determine Line

Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.

During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?

Input

The first line contains a single integer n (2 ≤ n ≤ 100) — the number of stops Arkady saw.

The next n lines describe the stops. Each of them starts with a single integer r (1 ≤ r ≤ 100) — the number of tram lines that stop there. r distinct integers follow, each one between 1 and 100, inclusive, — the line numbers. They can be in arbitrary order.

It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.

Output

Print all tram lines that Arkady could be in, in arbitrary order.

Examples

Input

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

Output

1 4

Input

5
1 1
10 10 9 8 7 100 5 4 3 99 1
5 1 2 3 4 5
5 4 1 3 2 5
4 10 1 5 3

Output

1

Note

Consider the first example. Arkady woke up three times. The first time he saw a stop with lines 1, 4, 6. The second time he saw a stop with lines 1, 4. The third time he saw a stop with lines 10, 5, 6, 4 and 1. He can be in a tram of one of two lines: 1 or 4.

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

def intersect(a, b):
    x = []
    for i in a:
        if i in b:
            x.append(i)
    return x

things = [input().split()[1:] for i in range(n)]
ans = things[0]
for i in range(1, n):
    ans = intersect(ans, things[i])

print(" ".join(ans))
```