1288_D. Minimax Problem

You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.

You have to choose two arrays a_i and a_j (1 ≤ i, j ≤ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k ∈ [1, m] b_k = max(a_{i, k}, a_{j, k}).

Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.

Input

The first line contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 8) — the number of arrays and the number of elements in each array, respectively.

Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 ≤ a_{x, y} ≤ 10^9).

Output

Print two integers i and j (1 ≤ i, j ≤ n, it is possible that i = j) — the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.

Example

Input

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

Output

1 5

```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)

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

# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default=2**30, 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 binary(x, length):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y

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------------------------------------
class TrieNode:
    def __init__(self):
        self.children = [None] * 26
        self.isEndOfWord = False
class Trie:
    def __init__(self):
        self.root = self.getNode()
    def getNode(self):
        return TrieNode()
    def _charToIndex(self, ch):
        return ord(ch) - ord('a')
    def insert(self, key):
        pCrawl = self.root
        length = len(key)
        for level in range(length):
            index = self._charToIndex(key[level])
            if not pCrawl.children[index]:
                pCrawl.children[index] = self.getNode()
            pCrawl = pCrawl.children[index]
        pCrawl.isEndOfWord = True
    def search(self, key):
        pCrawl = self.root
        length = len(key)
        for level in range(length):
            index = self._charToIndex(key[level])
            if not pCrawl.children[index]:
                return False
            pCrawl = pCrawl.children[index]
        return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
    def __init__(self, data):
        self.data = data
        self.count=0
        self.left = None  # left node for 0
        self.right = None  # right node for 1
class BinaryTrie:
    def __init__(self):
        self.root = Node(0)
    def insert(self, pre_xor):
        self.temp = self.root
        for i in range(31, -1, -1):
            val = pre_xor & (1 << i)
            if val:
                if not self.temp.right:
                    self.temp.right = Node(0)
                self.temp = self.temp.right
                self.temp.count+=1
            if not val:
                if not self.temp.left:
                    self.temp.left = Node(0)
                self.temp = self.temp.left
                self.temp.count += 1
        self.temp.data = pre_xor
    def query(self, xor):
        self.temp = self.root
        for i in range(31, -1, -1):
            val = xor & (1 << i)
            if not val:
                if self.temp.left and self.temp.left.count>0:
                    self.temp = self.temp.left
                elif self.temp.right:
                    self.temp = self.temp.right
            else:
                if self.temp.right and self.temp.right.count>0:
                    self.temp = self.temp.right
                elif self.temp.left:
                    self.temp = self.temp.left
            self.temp.count-=1
        return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
n,m=map(int,input().split())
l=[]
pm=2**m-1
for i in range(n):
    l.append(list(map(int,input().split())))
def find (x):
    s=set()
    d=defaultdict(int)
    for i in range(n):
        a=""
        for j in range(m):
            if l[i][j]>=x:
                a+='1'
            else:
                a+='0'
        d[int(a,2)]=i
        s.add(int(a,2))
    s=list(s)
    #print(s)
    for i in range(len(s)):
        for j in range(i,len(s)):
            if s[i]|s[j]==pm:
                return [d[s[i]]+1,d[s[j]]+1]
    return [-1,-1]
st=0
end=10**9
ans=(0,0)
while(st<=end):
    mid=(st+end)//2
    s=find(mid)
    if s[0]!=-1:
        ans=s
        st=mid+1
    else:
        end=mid-1
print(*ans)
```


1331_G. Lingua Romana

    per nextum in unam tum XI conscribementis fac sic
        vestibulo perlegementum da varo.
        morde varo.
        seqis cumula varum.
    cis

    per nextum in unam tum XI conscribementis fac sic
        seqis decumulamenta da varo.
        varum privamentum fodementum da aresulto.
        varum tum III elevamentum tum V multiplicamentum da bresulto.
        aresultum tum bresultum addementum da resulto.

        si CD tum resultum non praestantiam fac sic
            dictum sic f(%d) = %.2f cis tum varum tum resultum egresso describe.
            novumversum egresso scribe.
        cis
        si CD tum resultum praestantiam fac sic
            dictum sic f(%d) = MAGNA NIMIS! cis tum varum egresso describe.
            novumversum egresso scribe.
        cis
    cis

Input

The input consists of several integers, one per line. Each integer is between -50 and 50, inclusive.

Output

As described in the problem statement.

Example

Input

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

Output

f(10) = MAGNA NIMIS!
f(-9) = -3642.00
f(-8) = -2557.17
f(-7) = -1712.35
f(-6) = -1077.55
f(-5) = -622.76
f(-4) = -318.00
f(-3) = -133.27
f(-2) = -38.59
f(1) = 6.00
f(0) = 0.00

```python
l = [0 for i in range(11)]
for i in range(11):
    l[i] = int(input())
l.reverse()
for i in l:
    a = (i ** 3) * 5 + (abs(i) ** 0.5)
    if a > 400:
        print('f(' + str(i) + ') = MAGNA NIMIS!')
        continue
    print('f(' + str(i) + ') =', format(a, '.2f'))
```


1352_B. Same Parity Summands

You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).

In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i are odd at the same time.

If such a representation does not exist, then report it.

Input

The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Next, t test cases are given, one per line.

Each test case is two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100).

Output

For each test case print:

  * YES and the required values a_i, if the answer exists (if there are several answers, print any of them);
  * NO if the answer does not exist.

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

Example

Input

8
10 3
100 4
8 7
97 2
8 8
3 10
5 3
1000000000 9

Output

YES
4 2 4
YES
55 5 5 35
NO
NO
YES
1 1 1 1 1 1 1 1
NO
YES
3 1 1
YES
111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120

```python
T = int(input())
for test in range(T):
    n, k = map(int, input().split())
    if n % 2 != 0 and k % 2 == 0:
        print("NO")
    else:
        if n % 2 != 0: # Ak is odd
            if (n - (k-1)) > 0 and (n - (k-1)) % 2 == 1:
                print("YES")
                temp = [1 for _ in range(k-1)]+[(n - (k-1))]
                for i in temp:
                    print(i, end = ' ')
                print()
            else:
                print("NO")
        else: # n is even ak is even
            if (n - 2*(k-1)) > 1 and (n - 2* (k-1)) % 2 == 0:
                print("YES")
                temp = [2 for _ in range(k - 1)] + [(n - 2*(k - 1))]
                for i in temp:
                    print(i, end = ' ')
                print()
            else:
                if (n - (k - 1)) > 0 and (n - (k - 1)) % 2 == 1:
                    print("YES")
                    temp = [1 for _ in range(k - 1)] + [(n - (k - 1))]
                    for i in temp:
                        print(i, end=' ')
                    print()
                else:
                    print("NO")

```


1419_B. Stairs

Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.

A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has n stairs, then it is made of n columns, the first column is 1 cell high, the second column is 2 cells high, …, the n-th column if n cells high. The lowest cells of all stairs must be in the same row.

A staircase with n stairs is called nice, if it may be covered by n disjoint squares made of cells. All squares should fully consist of cells of a staircase.

This is how a nice covered staircase with 7 stairs looks like: <image>

Find out the maximal number of different nice staircases, that can be built, using no more than x cells, in total. No cell can be used more than once.

Input

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

The description of each test case contains a single integer x (1 ≤ x ≤ 10^{18}) — the number of cells for building staircases.

Output

For each test case output a single integer — the number of different nice staircases, that can be built, using not more than x cells, in total.

Example

Input

4
1
8
6
1000000000000000000

Output

1
2
1
30

Note

In the first test case, it is possible to build only one staircase, that consists of 1 stair. It's nice. That's why the answer is 1.

In the second test case, it is possible to build two different nice staircases: one consists of 1 stair, and another consists of 3 stairs. This will cost 7 cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is 2.

In the third test case, it is possible to build only one of two nice staircases: with 1 stair or with 3 stairs. In the first case, there will be 5 cells left, that may be used only to build a staircase with 2 stairs. This staircase is not nice, and Jett only builds nice staircases. That's why in this case the answer is 1. If Jett builds a staircase with 3 stairs, then there are no more cells left, so the answer is 1 again.

```python
ty=[1]
p=2
while(True):
    p=p*2
    ty.append(p-1)
    if(p>10**18):
        break
t=int(input())
for j in range(0,t):
    x=int(input())
    s=0
    c=0
    for o in ty:
        s=s+((o)*(o+1))//2
        if(s<=x):
            c=c+1
        else:
            break
    print(c)

```


1437_B. Reverse Binary Strings

You are given a string s of even length n. String s is binary, in other words, consists only of 0's and 1's.

String s has exactly n/2 zeroes and n/2 ones (n is even).

In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string.

What is the minimum number of operations you need to make string s alternating? A string is alternating if s_i ≠ s_{i + 1} for all i. There are two types of alternating strings in general: 01010101... or 10101010...

Input

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

The first line of each test case contains a single integer n (2 ≤ n ≤ 10^5; n is even) — the length of string s.

The second line of each test case contains a binary string s of length n (s_i ∈ {0, 1}). String s has exactly n/2 zeroes and n/2 ones.

It's guaranteed that the total sum of n over test cases doesn't exceed 10^5.

Output

For each test case, print the minimum number of operations to make s alternating.

Example

Input

3
2
10
4
0110
8
11101000

Output

0
1
2

Note

In the first test case, string 10 is already alternating.

In the second test case, we can, for example, reverse the last two elements of s and get: 0110 → 0101.

In the third test case, we can, for example, make the following two operations:

  1. 11101000 → 10101100;
  2. 10101100 → 10101010.

```python
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase

#New Imports

def solution():
    n = int(input())
    s = input()
    val = s.count('10')
    a1 = n//2 - val
    val = s.count('01')
    a2 = n//2 - val
    print(min(a1,a2))
    return

def main():
    testcases = 1
    testcases = int(input())
    for _ in range(testcases):
        solution()

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

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


1461_F. Mathematical Expression

Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw n numbers a_1, a_2, …, a_n without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers in a way that would make the resulting expression's value as large as possible. To find out which symbols were available the teacher has given Barbara a string s which contained that information.

<image>

It's easy to notice that Barbara has to place n - 1 symbols between numbers in total. The expression must start with a number and all symbols must be allowed (i.e. included in s). Note that multiplication takes precedence over addition or subtraction, addition and subtraction have the same priority and performed from left to right. Help Barbara and create the required expression!

Input

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

The second line of the input contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 9), where a_i is the i-th element of a.

The third line of the input contains the string s (1 ≤ |s| ≤ 3) — symbols allowed in the expression. It is guaranteed that the string may only consist of symbols "-", "+" and "*". It is also guaranteed that all symbols in the string are distinct.

Output

Print n numbers separated by n - 1 symbols — a mathematical expression with the greatest result. If there are multiple equally valid results — output any one of them.

Examples

Input

3
2 2 0
+-*

Output

2*2-0

Input

4
2 1 1 2
+*

Output

2+1+1+2

Note

The following answers also fit the first example: "2+2+0", "2+2-0", "2*2+0".

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

n = int(input())
a = list(map(int,input().split()))
ops = input().strip()

if len(ops) == 1:
    print(ops.join(map(str, a)))

elif '+' in ops and '*' in ops:
    seqs = [[a[0]]]
    output = []

    # split into seqs of all 0's or non 0's
    # every seq in seqs is a list of all 0's or non 0's
    for i in range(1,n):
        if a[i] == 0:
            if seqs[-1][-1] == 0:
                seqs[-1].append(a[i])
            else:
                seqs.append([a[i]])
        else:
            if seqs[-1][-1] == 0:
                seqs.append([a[i]])
            else:
                seqs[-1].append(a[i])

    for seq in seqs:
        if seq[0] == 0:
            # all 0
            output.append('+'.join(map(str,seq)))
        else:
            # if prod >= 2*n, using addition is never optimal
            prod = 1
            for i in seq:
                prod *= i
                if prod >= 2 * n:
                    break
            if prod >= 2 * n:
                new_seq = ''
                l = 0
                r = len(seq) - 1
                for i in range(len(seq)):
                    if seq[i] != 1:
                        l = i
                        break
                for i in range(len(seq)-1,-1,-1):
                    if seq[i] != 1:
                        r = i
                        break

                if l != 0:
                    new_seq += '+'.join('1'*l) + '+'
                new_seq += '*'.join(map(str,seq[l:r+1]))
                if r != len(seq)-1:
                    new_seq += '+' + '+'.join('1' * (len(seq) - 1 - r))

                output.append(new_seq)
                continue

            # prod < 2*n so max length of seq after combining 1's is 2*log(2*n)
            # use dp to find optimal operations
            b = []
            lst = -1
            for i in seq:
                if i == 1:
                    if lst != 1:
                        b.append([-1,1])
                    else:
                        b[-1][-1] += 1
                else:
                    b.append([0,i])

                lst = i

            # + -> 0 | * -> 1
            last_state = [[None]*2 for i in range(len(b)+1)]
            dp = [[-10**9]*2 for i in range(len(b)+1)]
            dp[0][0] = 0
            dp[0][1] = 0
            for i in range(len(b)):
                # find state with mx val with i-1 elements used
                mx = None
                state = None
                if dp[i][0] > dp[i][1]:
                    mx = dp[i][0]
                    state = [i,0]
                else:
                    mx = dp[i][1]
                    state = [i,1]

                # add
                if mx + b[i][1] > dp[i+1][0]:
                    dp[i+1][0] = mx + b[i][1]
                    last_state[i+1][0] = ['+', state]

                # multiply
                prod = 1
                for j in range(i,len(b)):
                    if b[j][0] == 0:
                        prod *= b[j][1]
                    if mx + prod > dp[j+1][1]:
                        dp[j+1][1] = mx + prod
                        last_state[j+1][1] = ['*', state]

            # go in reverse to reconstruct sequence
            solved_seq = []
            state = None
            if dp[len(b)][1] > dp[len(b)][0]:
                state = [len(b),1]
            else:
                state = [len(b),0]

            while state[0] != 0:
                next_state = last_state[state[0]][state[1]][1]
                operation = last_state[state[0]][state[1]][0]

                for i in range(state[0] - 1, next_state[0]-1,-1):
                    # will add extra operation at end of output, but we can remove it later
                    if b[i][0] == -1:
                        solved_seq.append(operation.join('1' * b[i][1]) + operation)
                    else:
                        solved_seq.append(str(b[i][1]) + operation)
                if operation == '*':
                    solved_seq[-1] = solved_seq[-1][:-1] + '+'

                state = next_state

            # remove extra operation at beg(was at end but we reversed)
            output.append(''.join(solved_seq)[-2::-1])

    print('+'.join(output))

elif '+' in ops:
    print('+'.join(map(str,a)))

elif '*' in ops:
    if 0 in a:
        output = []
        all_mult = 0

        for i in range(n-1):
            if a[i+1] == 0 and not all_mult:
                output.extend([a[i],'-'])
                all_mult = 0
            else:
                output.extend([a[i],'*'])
        output.append(a[-1])

        print(*output,sep='')

    else:
        print('*'.join(map(str, a)))

```


1487_A. Arena

n heroes fight against each other in the Arena. Initially, the i-th hero has level a_i.

Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute).

When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by 1.

The winner of the tournament is the first hero that wins in at least 100^{500} fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament.

Calculate the number of possible winners among n heroes.

Input

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

Each test case consists of two lines. The first line contains one integer n (2 ≤ n ≤ 100) — the number of heroes. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100), where a_i is the initial level of the i-th hero.

Output

For each test case, print one integer — the number of possible winners among the given n heroes.

Example

Input

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

Output

1
0
3

Note

In the first test case of the example, the only possible winner is the first hero.

In the second test case of the example, each fight between the heroes results in nobody winning it, so the tournament lasts forever and there is no winner.

```python
tests = int(input())
for t in range(tests):
    n = int(input())
    heroes = list(map(int, input().split(' ')))

    m = min(heroes)
    print(sum([1 for x in heroes if x > m]))
```


1538_C. Number of Pairs

You are given an array a of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r).

For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:

  * i=1 and j=2 (4 ≤ 5 + 1 ≤ 7);
  * i=1 and j=3 (4 ≤ 5 + 2 ≤ 7).

Input

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

The first line of each test case contains three integers n, l, r (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the array and the limits on the sum in the pair.

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

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

Output

For each test case, output a single integer — the number of index pairs (i, j) (i < j), such that l ≤ a_i + a_j ≤ r.

Example

Input

4
3 4 7
5 1 2
5 5 8
5 1 2 4 3
4 100 1000
1 1 1 1
5 9 13
2 5 5 1 1

Output

2
7
0
1

```python
# Author: Javier Bórquez

import os
import sys
import bisect

def main():
  fastReadInt = sys.stdin.buffer.readline
  def fastReadStr(): return sys.stdin.buffer.readline().decode('utf-8').strip()
  def fastWrite(ans): return sys.stdout.buffer.write(str(str(ans) + "\n").encode('utf-8'))
  def fastWriteList(ans): return sys.stdout.buffer.write(str(" ".join(map(str, ans)) + "\n").encode('utf-8'))

  DEBUG = 'DEBUG' in os.environ
  def debug(*args):
    if DEBUG:
      print(">", *args)

  def find_le(a, x):
      'Find rightmost value less than or equal to x'
      i = bisect.bisect_right(a, x)
      if i:
          return i - 1
      return -1

  def find_ge(a, x):
      'Find leftmost item greater than or equal to x'
      i = bisect.bisect_left(a, x)
      if i != len(a):
          return i
      return -1

  def solution(n, l, r, value):
    debug("")
    value.sort()
    debug(n, l, r, value)

    res = 0

    for ni in range(0, len(value)):
      n = value[ni]

      upper = find_le(value, r - n)
      lower = find_ge(value, l - n)

      if upper != -1 and lower != -1:
        debug(ni, [lower, upper])
        res += upper - lower + 1
        if ni >= lower and ni <= upper:
          res -= 1

    fastWrite(res // 2)

  # N lines, then N int
  for t in range(int(fastReadInt())):
    nlr = list(map(int, fastReadInt().split()))
    n = nlr[0]
    l = nlr[1]
    r = nlr[2]
    solution(n, l, r, list(map(int, fastReadInt().split())))

main()

```


231_E. Cactus

A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle.

A simple cycle in a undirected graph is a sequence of distinct vertices v1, v2, ..., vt (t > 2), such that for any i (1 ≤ i < t) exists an edge between vertices vi and vi + 1, and also exists an edge between vertices v1 and vt.

A simple path in a undirected graph is a sequence of not necessarily distinct vertices v1, v2, ..., vt (t > 0), such that for any i (1 ≤ i < t) exists an edge between vertices vi and vi + 1 and furthermore each edge occurs no more than once. We'll say that a simple path v1, v2, ..., vt starts at vertex v1 and ends at vertex vt.

You've got a graph consisting of n vertices and m edges, that is a vertex cactus. Also, you've got a list of k pairs of interesting vertices xi, yi, for which you want to know the following information — the number of distinct simple paths that start at vertex xi and end at vertex yi. We will consider two simple paths distinct if the sets of edges of the paths are distinct.

For each pair of interesting vertices count the number of distinct simple paths between them. As this number can be rather large, you should calculate it modulo 1000000007 (109 + 7).

Input

The first line contains two space-separated integers n, m (2 ≤ n ≤ 105; 1 ≤ m ≤ 105) — the number of vertices and edges in the graph, correspondingly. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n) — the indexes of the vertices connected by the i-th edge.

The next line contains a single integer k (1 ≤ k ≤ 105) — the number of pairs of interesting vertices. Next k lines contain the list of pairs of interesting vertices: the i-th line contains two space-separated numbers xi, yi (1 ≤ xi, yi ≤ n; xi ≠ yi) — the indexes of interesting vertices in the i-th pair.

It is guaranteed that the given graph is a vertex cactus. It is guaranteed that the graph contains no loops or multiple edges. Consider the graph vertices are numbered from 1 to n.

Output

Print k lines: in the i-th line print a single integer — the number of distinct simple ways, starting at xi and ending at yi, modulo 1000000007 (109 + 7).

Examples

Input

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

Output

2
2
2
4
4
1

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

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

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

@bootstrap
def dfs1(cur,prev,v):
    depth[cur] = depth[prev] + 1
    parent[cur][0] = prev
    blacks[cur]=v
    if val[cur]:
        blacks[cur]+=1
    for i in tree[cur]:
        if (i != prev):
            yield dfs1(i, cur,blacks[cur])

    yield

def precomputeSparseMatrix(n):
    for i in range(1,level):
        for node in range(1,n+1):
            if (parent[node][i-1] != -1):
                parent[node][i] =parent[parent[node][i-1]][i-1]

def lca(u,v):
    if (depth[v] < depth[u]):
        u,v=v,u

    diff = depth[v] - depth[u]

    for i in range(level):
        if ((diff >> i) & 1):
            v = parent[v][i]

    if (u == v):
        return u

    i=level-1
    while(i>=0):

        if (parent[u][i] != parent[v][i]):
            u = parent[u][i]
            v = parent[v][i]

        i+=-1

    return parent[u][0]

@bootstrap
def dfs(u,p):

    global curr

    for j in adj[u]:
        if j!=p:
            if id[j]==0:
                id[j]=id[u]+1
                yield dfs(j,u)

            elif id[u]>id[j]:

                up[u]=curr
                down[j]=curr
                curr+=1
    yield

@bootstrap
def dfs2(u,p):

    vis[u]=1
    for j in adj[u]:
        if not vis[j]:
            yield dfs2(j,u)

    if up[u]:
        id[u]=up[u]

    else:
        id[u]=u
        for j in adj[u]:
            if j!=p:
                if id[j]!=j and down[j]==0:

                    id[u]=id[j]
    yield

n,m=map(int,input().split())
adj=[[] for i in range(n+1)]
edges=[]
for j in range(m):
    u,v=map(int,input().split())
    edges.append([u,v])
    adj[u].append(v)
    adj[v].append(u)

up=defaultdict(lambda:0)
down=defaultdict(lambda:0)

curr=n+1
id=[]
vis=[]
val=[]
tree=[]
depth=[]
for j in range(n+1):
    id.append(0)
    vis.append(0)
    val.append(0)
    tree.append([])
    depth.append(0)

id[1]=1
dfs(1,0)
dfs2(1,0)
res=sorted(list(set(id[1:])))
up=defaultdict(lambda:0)
l=len(res)
for j in range(l):
    up[res[j]]=j+1

d=defaultdict(lambda:0)
for j in range(1,n+1):
    id[j]=up[id[j]]
    d[id[j]]+=1
    if d[id[j]]>1:
        val[id[j]]=1

level=17

parent=[[0 for i in range(level)] for j in range(l+1)]
blacks=[0]*(l+1)
d=defaultdict(lambda:0)
for j in edges:
    u,v=j[0],j[1]
    p,q=id[u],id[v]
    if not d[p,q] and p!=q:
        tree[p].append(q)
        tree[q].append(p)

    d[p,q]=1
    d[q,p]=1

dfs1(1,0,0)

precomputeSparseMatrix(l)

k=int(input())
mod=10**9+7
value=[1]
for j in range(1,l+1):
    value.append((2*value[-1])%(mod))
for j in range(k):
    a,b=map(int,input().split())
    u1,v1=id[a],id[b]
    lc=lca(u1,v1)

    res=value[blacks[u1]+blacks[v1]-2*blacks[lc]]

    if val[lc]:
        res*=2

    print(res%mod)
```


257_D. Sum

Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).

Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.

Input

The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.

It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).

Output

In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.

Examples

Input

4
1 2 3 5

Output

+++-

Input

3
3 3 5

Output

++-

```python
#!/usr/bin/python3

n = int(input())
a = list(map(int, input().split()))
s = a[-1]
ans = ['+']
for v in reversed(a[:-1]):
    if s > 0:
        s -= v
        ans.append('-')
    else:
        s += v
        ans.append('+')
if 0 <= s <= a[-1]:
    print(''.join(reversed(ans)))
else:
    s = -a[-1]
    ans = ['-']
    for v in reversed(a[:-1]):
        if s > 0:
            s -= v
            ans.append('-')
        else:
            s += v
            ans.append('+')
    if 0 <= s <= a[-1]:
        print(''.join(reversed(ans)))
    else:
        s = a[-1]
        ans = ['+']
        for v in reversed(a[:-1]):
            if s >= 0:
                s -= v
                ans.append('-')
            else:
                s += v
                ans.append('+')
        if 0 <= s <= a[-1]:
            print(''.join(reversed(ans)))
        else:
            s = -a[-1]
            ans = ['-']
            for v in reversed(a[:-1]):
                if s >= 0:
                    s -= v
                    ans.append('-')
                else:
                    s += v
                    ans.append('+')
            print(''.join(reversed(ans)))

```


32_D. Constellation

A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true:

  * the 2nd is on the same vertical line as the 1st, but x squares up
  * the 3rd is on the same vertical line as the 1st, but x squares down
  * the 4th is on the same horizontal line as the 1st, but x squares left
  * the 5th is on the same horizontal line as the 1st, but x squares right

Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal — the one, whose central star if higher than the central star of the other one; if their central stars are at the same level — the one, whose central star is to the left of the central star of the other one.

Your task is to find the constellation with index k by the given Berland's star map.

Input

The first line contains three integers n, m and k (1 ≤ n, m ≤ 300, 1 ≤ k ≤ 3·107) — height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right — (n, m). Then there follow n lines, m characters each — description of the map. j-th character in i-th line is «*», if there is a star in the corresponding square, and «.» if this square is empty.

Output

If the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each — coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.

Examples

Input

5 6 1
....*.
...***
....*.
..*...
.***..

Output

2 5
1 5
3 5
2 4
2 6

Input

5 6 2
....*.
...***
....*.
..*...
.***..

Output

-1

Input

7 7 2
...*...
.......
...*...
*.***.*
...*...
.......
...*...

Output

4 4
1 4
7 4
4 1
4 7

```python
import sys
from array import array  # noqa: F401

def input():
    return sys.stdin.buffer.readline().decode('utf-8')

n, m, k = map(int, input().split())
a = [tuple(map(lambda c: c == '*', input().rstrip())) for _ in range(n)]
cnt = [0] * 400

for i in range(1, n - 1):
    for j in range(1, m - 1):
        if not a[i][j]:
            continue
        for rad, ui, di, lj, rj in zip(range(1, 400), range(i - 1, -1, -1), range(i + 1, n), range(j - 1, -1, -1), range(j + 1, m)):
            if all((a[ui][j], a[di][j], a[i][lj], a[i][rj])):
                cnt[rad] += 1

rad = -1
for i in range(300):
    cnt[i + 1] += cnt[i]
    if cnt[i] >= k:
        rad = i
        k -= cnt[i - 1]
        break
else:
    print(-1)
    exit()

for i in range(rad, n - rad):
    for j in range(rad, m - rad):
        if all((a[i][j], a[i - rad][j], a[i + rad][j], a[i][j - rad], a[i][j + rad])):
            k -= 1
            if k == 0:
                print(f'{i+1} {j+1}\n{i-rad+1} {j+1}\n{i+rad+1} {j+1}\n{i+1} {j-rad+1}\n{i+1} {j+rad+1}')
                exit()

```


351_B. Jeff and Furik

Jeff has become friends with Furik. Now these two are going to play one quite amusing game.

At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.

Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.

You can consider that the coin shows the heads (or tails) with the probability of 50 percent.

Input

The first line contains integer n (1 ≤ n ≤ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation p. The numbers are separated by spaces.

Output

In a single line print a single real value — the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.

Examples

Input

2
1 2

Output

0.000000

Input

5
3 5 2 4 1

Output

13.000000

Note

In the first test the sequence is already sorted, so the answer is 0.


420_A. Start Up

Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?

The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.

There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.

Input

The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font:

<image>

Output

Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes).

Examples

Input

AHA

Output

YES

Input

Z

Output

NO

Input

XO

Output

NO

```python
'''input
XO
'''
s = input()
if all(s[x] == s[~x] for x in range(len(s)//2)):
	if any(y not in "AHIMOTUVWXY" for y in s[:len(s)//2+1]):
		print("NO")
	else:
		print("YES")
else:
	print("NO")
```


490_E. Restoring Increasing Sequence

Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit.

Restore the the original sequence knowing digits remaining on the board.

Input

The first line of the input contains integer n (1 ≤ n ≤ 105) — the length of the sequence. Next n lines contain one element of the sequence each. Each element consists only of digits and question marks. No element starts from digit 0. Each element has length from 1 to 8 characters, inclusive.

Output

If the answer exists, print in the first line "YES" (without the quotes). Next n lines must contain the sequence of positive integers — a possible variant of Peter's sequence. The found sequence must be strictly increasing, it must be transformed from the given one by replacing each question mark by a single digit. All numbers on the resulting sequence must be written without leading zeroes. If there are multiple solutions, print any of them.

If there is no answer, print a single line "NO" (without the quotes).

Examples

Input

3
?
18
1?

Output

YES
1
18
19

Input

2
??
?

Output

NO

Input

5
12224
12??5
12226
?0000
?00000

Output

YES
12224
12225
12226
20000
100000

```python
def solve(s, t, i, l):
    if i == l:
        return False
    if s[i] == "?":
        if solve(s, t, i + 1, l):
            s[i] = t[i]
            return True
        elif t[i] == "9":
            return False
        s[i] = nxt[t[i]]
        for j in range(i, l):
            if s[j] == "?":
                s[j] = "0"
        return True
    elif s[i] > t[i]:
        for j in range(i, l):
            if s[j] == "?":
                s[j] = "0"
        return True
    elif s[i] < t[i]:
        return False
    else:
        return solve(s, t, i + 1, l)

n = int(input())
a = [list(input()) for _ in range(n)]
p = ["0"]
nxt = {str(x): str(x + 1) for x in range(9)}

for i, ai in enumerate(a):
    if len(p) > len(ai):
        print("NO")
        break
    if len(p) < len(ai):
        if a[i][0] == "?":
            a[i][0] = "1"
        for j in range(len(ai)):
            if a[i][j] == "?":
                a[i][j] = "0"
    elif not solve(a[i], p, 0, len(ai)):
        print("NO")
        break
    p = a[i]
else:
    print("YES")
    print("\n".join("".join(line) for line in a))
```


514_E. Darth Vader and Tree

When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most x from the root. The distance is the sum of the lengths of edges on the path between nodes.

But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' — you may ask. It's just that he feels superior knowing that only he can solve this problem.

Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo 109 + 7.

Input

The first line contains two space-separated integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 109) — the number of children of each node and the distance from the root within the range of which you need to count the nodes.

The next line contains n space-separated integers di (1 ≤ di ≤ 100) — the length of the edge that connects each node with its i-th child.

Output

Print a single number — the number of vertexes in the tree at distance from the root equal to at most x.

Examples

Input

3 3
1 2 3

Output

8

Note

Pictures to the sample (the yellow color marks the nodes the distance to which is at most three)

<image>

```python
# fast io
from sys import stdin
_data = iter(stdin.read().split('\n'))
input = lambda: next(_data)

N = 101
MOD = 1000000007

def mul_vec_mat(v, a):
    c = [0] * N
    for i in range(N):
        c[i] = sum(a[j][i] * v[j] % MOD for j in range(N)) % MOD
    return c

def mul_vec_sparse_mat(v, a):
    c = [0] * N
    for i in range(N):
        c[i] = sum(x * v[j] % MOD for j, x in a[i]) % MOD
    return c

_, x = [int(v) for v in input().split()]
a = [[0] * N for i in range(N)]
a[0][0] = 1
a[N - 1][0] = 1
for i in range(1, N - 1):
    a[i][i + 1] = 1
for d in map(int, input().split()):
    a[N - 1][N - d] += 1
sa = [[] for i in range(N)]
for i in range(N):
    for j in range(N):
        if a[i][j] != 0:
            sa[j].append((i, a[i][j]))
r = [[1 if i == j else 0 for j in range(N)] for i in range(N)]
while x > 0:
    if x & 1:
        r[0] = mul_vec_mat(r[0], a)
        r[1] = mul_vec_mat(r[1], a)
    aa = [[0] * N for i in range(N)]
    aa[0] = mul_vec_mat(a[0], a)
    aa[1] = mul_vec_mat(a[1], a)
    for i in range(2, N):
        aa[i] = mul_vec_sparse_mat(aa[i - 1], sa)
    a = aa
    x >>= 1
for i in range(2, N):
    r[i] = mul_vec_sparse_mat(r[i - 1], sa)
b = [0] * N
b[0] = 1
b[N - 1] = 1
print(sum(r[N - 1][i] * b[i] % MOD for i in range(N)) % MOD)
```


569_B. Inventory

Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.

During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.

You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.

Input

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

The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items.

Output

Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.

Examples

Input

3
1 3 2

Output

1 3 2

Input

4
2 2 3 3

Output

2 1 3 4

Input

1
2

Output

1

Note

In the first test the numeration is already a permutation, so there is no need to change anything.

In the second test there are two pairs of equal numbers, in each pair you need to replace one number.

In the third test you need to replace 2 by 1, as the numbering should start from one.

```python
n = int(input())
fix = list()
factors = set(range(1, n + 1))
for i in map(int, input().split()):
    if i in factors:
        factors.remove(i)
        fix.append(i)
    else:
        fix.append(None)
print(' '.join(str(factors.pop()) if i is None else str(i) for i in fix))
```


631_D. Messenger

Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve.

All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (li, ci), where li is the length of the i-th block and ci is the corresponding letter. Thus, the string s may be written as the sequence of pairs <image>.

Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if tptp + 1...tp + |s| - 1 = s, where ti is the i-th character of string t.

Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as <image>, <image>, <image>...

Input

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of blocks in the strings t and s, respectively.

The second line contains the descriptions of n parts of string t in the format "li-ci" (1 ≤ li ≤ 1 000 000) — the length of the i-th part and the corresponding lowercase English letter.

The second line contains the descriptions of m parts of string s in the format "li-ci" (1 ≤ li ≤ 1 000 000) — the length of the i-th part and the corresponding lowercase English letter.

Output

Print a single integer — the number of occurrences of s in t.

Examples

Input

5 3
3-a 2-b 4-c 3-a 2-c
2-a 2-b 1-c

Output

1

Input

6 1
3-a 6-b 7-a 4-c 8-e 2-a
3-a

Output

6

Input

5 5
1-h 1-e 1-l 1-l 1-o
1-w 1-o 1-r 1-l 1-d

Output

0

Note

In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2.

In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14.

```python
def ziped(a):
    p = []
    for i in a:
        x = int(i.split('-')[0])
        y = i.split('-')[1]
        if len(p) > 0 and p[-1][1] == y:
                p[-1][0] += x
        else:
                p.append([x, y])
    return p

def solve(a, b , c):

    ans = 0
    if len(b) == 1:
        for token in a:
            #print("token",token)
            if c(token, b[0]):
                ans += token[0] - b[0][0] + 1
        return ans

    if len(b) == 2:
        for i in range(len(a) - 1):
            if c(a[i], b[0]) and c(a[i + 1], b[-1]):
                ans += 1
        return ans

    v = b[1 : -1] + [[100500, '#']] + a
    p = [0] * len(v)
    for i in range(1, len(v)):
        j = p[i - 1]
        while j > 0 and v[i] != v[j]:
            j = p[j - 1]
        if v[i] == v[j]:
            j += 1
        p[i] = j

    for i in range(len(v) - 1):
        if p[i] == len(b) - 2 and c(v[i - p[i]], b[0]) and c(v[i + 1], b[-1]):
            ans += 1
    return ans

n, m = map(int, input().split())
a = ziped(input().split())
b = ziped(input().split())
print(solve(a, b, lambda x, y: x[1] == y[1] and x[0] >= y[0]))

```


660_B. Seating On Bus

Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.

Consider that m (m ≤ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:

1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.

After occupying all the window seats (for m > 2n) the non-window seats are occupied:

1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.

All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.

1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat.

<image> The seating for n = 9 and m = 36.

You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus.

Input

The only line contains two integers, n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 4n) — the number of pairs of rows and the number of passengers.

Output

Print m distinct integers from 1 to m — the order in which the passengers will get off the bus.

Examples

Input

2 7

Output

5 1 6 2 7 3 4

Input

9 36

Output

19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18

```python

n,m = map(int,input().split())

for k in range(1,2*n +1):
    num = 2 *n +k
    if num <= m:
        print(num, end=" ")
    num = k
    if num <= m:
        print(num, end=" ")

```


74_C. Chessboard Billiard

Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.

More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed.

<image>

It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located.

You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size.

Input

The first line contains two integers n and m (2 ≤ n, m ≤ 106).

Output

Print a single number, the maximum possible number of billiard balls that do not pairwise beat each other.

Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator).

Examples

Input

3 4

Output

2

Input

3 3

Output

3

```python
import math
n,m=map(int,input().split())
print(math.gcd(n-1,m-1)+1)

```


773_B. Dynamic Problem Scoring

Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.

For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round.

<image>

Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to 1 / 4, and the problem's maximum point value is equal to 1500.

If the problem's maximum point value is equal to x, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses x / 250 points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with 2000·(1 - 40 / 250) = 1680 points for this problem.

There are n participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem.

With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing.

Unfortunately, Vasya is a cheater. He has registered 109 + 7 new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved.

Vasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts.

Find the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal.

Input

The first line contains a single integer n (2 ≤ n ≤ 120) — the number of round participants, including Vasya and Petya.

Each of the next n lines contains five integers ai, 1, ai, 2..., ai, 5 ( - 1 ≤ ai, j ≤ 119) — the number of minutes passed between the beginning of the round and the submission of problem j by participant i, or -1 if participant i hasn't solved problem j.

It is guaranteed that each participant has made at least one successful submission.

Vasya is listed as participant number 1, Petya is listed as participant number 2, all the other participants are listed in no particular order.

Output

Output a single integer — the number of new accounts Vasya needs to beat Petya, or -1 if Vasya can't achieve his goal.

Examples

Input

2
5 15 40 70 115
50 45 40 30 15

Output

2

Input

3
55 80 10 -1 -1
15 -1 79 60 -1
42 -1 13 -1 -1

Output

3

Input

5
119 119 119 119 119
0 0 0 0 -1
20 65 12 73 77
78 112 22 23 11
1 78 60 111 62

Output

27

Input

4
-1 20 40 77 119
30 10 73 50 107
21 29 -1 64 98
117 65 -1 -1 -1

Output

-1

Note

In the first example, Vasya's optimal strategy is to submit the solutions to the last three problems from two new accounts. In this case the first two problems will have the maximum point value of 1000, while the last three problems will have the maximum point value of 500. Vasya's score will be equal to 980 + 940 + 420 + 360 + 270 = 2970 points, while Petya will score just 800 + 820 + 420 + 440 + 470 = 2950 points.

In the second example, Vasya has to make a single unsuccessful submission to any problem from two new accounts, and a single successful submission to the first problem from the third new account. In this case, the maximum point values of the problems will be equal to 500, 1500, 1000, 1500, 3000. Vasya will score 2370 points, while Petya will score just 2294 points.

In the third example, Vasya can achieve his goal by submitting the solutions to the first four problems from 27 new accounts. The maximum point values of the problems will be equal to 500, 500, 500, 500, 2000. Thanks to the high cost of the fifth problem, Vasya will manage to beat Petya who solved the first four problems very quickly, but couldn't solve the fifth one.

```python
import sys

inf = 10**9 + 7

def solve():
    n = int(sys.stdin.readline())

    v = [int(vi) for vi in sys.stdin.readline().split()] # Vesya
    p = [int(pi) for pi in sys.stdin.readline().split()] # Petya

    cnt = [0]*5

    for i in range(5):
        if v[i] != -1:
            cnt[i] += 1
        if p[i] != -1:
            cnt[i] += 1

    for i in range(n - 2):
        a = [int(ai) for ai in sys.stdin.readline().split()]

        for j in range(5):
            if a[j] != -1:
                cnt[j] += 1

    for i in range(4000):
        if check(n, v, p, cnt, i):
            print(i)
            return

    print(-1)

def check(n, v, p, cnt, m):
    tot = n + m
    solved = cnt[:]
    dif = 0

    for i in range(5):
        if p[i] != -1 and v[i] > p[i]:
            solved[i] += m

    for i in range(5):
        if solved[i]*2 > tot:
            max_score = 500
        elif solved[i]*4 > tot:
            max_score = 1000
        elif solved[i]*8 > tot:
            max_score = 1500
        elif solved[i]*16 > tot:
            max_score = 2000
        elif solved[i]*32 > tot:
            max_score = 2500
        else:
            max_score = 3000

        if v[i] == p[i] == -1:
            pass
        elif v[i] == -1:
            dif -= max_score * (250 - p[i]) // 250
        elif p[i] == -1:
            dif += max_score * (250 - v[i]) // 250
        else:
            dif += max_score * (p[i] - v[i]) // 250

    return dif > 0

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


798_A. Mike and palindrome

Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.

A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.

Input

The first and single line contains string s (1 ≤ |s| ≤ 15).

Output

Print "YES" (without quotes) if Mike can change exactly one character so that the resulting string is palindrome or "NO" (without quotes) otherwise.

Examples

Input

abccaa

Output

YES

Input

abbcca

Output

NO

Input

abcda

Output

YES

```python
import sys
import math
import itertools
import collections

def getdict(n):
    d = {}
    if type(n) is list or type(n) is str:
        for i in n:
            if i in d:
                d[i] += 1
            else:
                d[i] = 1
    else:
        for i in range(n):
            t = ii()
            if t in d:
                d[t] += 1
            else:
                d[t] = 1
    return d
def divs(n, start=1):
    r = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if (n % i == 0):
            if (n / i == i):
                r.append(i)
            else:
                r.extend([i, n // i])
    return r
def cdiv(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a*b) // math.gcd(a, b)
def wr(arr): return ''.join(map(str, arr))
def revn(n): return int(str(n)[::-1])
def prime(n):
    if n == 2: return True
    if n % 2 == 0 or n <= 1: return False
    sqr = int(math.sqrt(n)) + 1
    for d in range(3, sqr, 2):
        if n % d == 0: return False
    return True
def convn(number, base=3):
    newnumber = ''
    while number > 0:
        newnumber = str(number % base) + newnumber
        number //= base
    return newnumber

s = input()
t = 0
for i in range(len(s) // 2):
    if s[i] != s[-i -1]:
        t += 1
if len(s) % 2 == 1 and t < 2 or len(s) % 2 == 0 and t == 1:
    print('YES')
else:
    print('NO')

```


818_C. Sofa Thief

Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss?

Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs to him as they all looked the same!

The storehouse is represented as matrix n × m. Every sofa takes two neighbouring by some side cells. No cell is covered by more than one sofa. There can be empty cells.

Sofa A is standing to the left of sofa B if there exist two such cells a and b that xa < xb, a is covered by A and b is covered by B. Sofa A is standing to the top of sofa B if there exist two such cells a and b that ya < yb, a is covered by A and b is covered by B. Right and bottom conditions are declared the same way.

Note that in all conditions A ≠ B. Also some sofa A can be both to the top of another sofa B and to the bottom of it. The same is for left and right conditions.

The note also stated that there are cntl sofas to the left of Grandpa Maks's sofa, cntr — to the right, cntt — to the top and cntb — to the bottom.

Grandpa Maks asks you to help him to identify his sofa. It is guaranteed that there is no more than one sofa of given conditions.

Output the number of Grandpa Maks's sofa. If there is no such sofa that all the conditions are met for it then output -1.

Input

The first line contains one integer number d (1 ≤ d ≤ 105) — the number of sofas in the storehouse.

The second line contains two integer numbers n, m (1 ≤ n, m ≤ 105) — the size of the storehouse.

Next d lines contains four integer numbers x1, y1, x2, y2 (1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m) — coordinates of the i-th sofa. It is guaranteed that cells (x1, y1) and (x2, y2) have common side, (x1, y1)  ≠  (x2, y2) and no cell is covered by more than one sofa.

The last line contains four integer numbers cntl, cntr, cntt, cntb (0 ≤ cntl, cntr, cntt, cntb ≤ d - 1).

Output

Print the number of the sofa for which all the conditions are met. Sofas are numbered 1 through d as given in input. If there is no such sofa then print -1.

Examples

Input

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

Output

1

Input

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

Output

2

Input

2
2 2
2 1 1 1
1 2 2 2
1 0 0 0

Output

-1

Note

Let's consider the second example.

  * The first sofa has 0 to its left, 2 sofas to its right ((1, 1) is to the left of both (5, 5) and (5, 4)), 0 to its top and 2 to its bottom (both 2nd and 3rd sofas are below).
  * The second sofa has cntl = 2, cntr = 1, cntt = 2 and cntb = 0.
  * The third sofa has cntl = 2, cntr = 1, cntt = 1 and cntb = 1.

So the second one corresponds to the given conditions.

In the third example

  * The first sofa has cntl = 1, cntr = 1, cntt = 0 and cntb = 1.
  * The second sofa has cntl = 1, cntr = 1, cntt = 1 and cntb = 0.

And there is no sofa with the set (1, 0, 0, 0) so the answer is -1.

```python
import sys
from collections import defaultdict as dd
from collections import deque

pl=1
from math import *
import copy
#sys.setrecursionlimit(10**6)
if pl:
	input=sys.stdin.readline

def li():
	return [int(xxx) for xxx in input().split()]
def fi():
	return int(input())
def si():
	return list(input().rstrip())
def mi():
	return 	map(int,input().split())

d=[]
from bisect import *

from itertools import permutations
from bisect import *
f=[0 for i in range(100)]

for i in range(1,100):
	if i==1:
		f[i]=1
	else:
		f[i]=2*f[i-1]+1

#print(f[:15])
def rec(n,k):
	s=[]
	while n!=0:
		n,r=n//k,n%k
		#print(n,r)
		if r<0:
			r-=k
			n+=1
		#print(s,n,r)
		s.append(r)
	return s
n=fi()
p,q=mi()
pp=[]
l=[];r=[];u=[];d=[]
for i in range(n):
	x1,y1,x2,y2=mi()
	x1,x2=min(x1,x2),max(x1,x2)
	y1,y2=min(y1,y2),max(y1,y2)
	l.append(x1)
	r.append(-x2)
	u.append(y1)
	d.append(-y2)
	pp.append([x1,x2,y1,y2])
l.sort()
r.sort()
u.sort()
d.sort()
#print(l,r,u,d)
f=[[0,0,0,0] for i in range(n+1)]
for i in range(n):
	f[i][0]=bisect_left(l,pp[i][1])
	if pp[i][0]<pp[i][1]:
		f[i][0]-=1
	f[i][1]=bisect_left(r,-pp[i][0])
	if pp[i][0]<pp[i][1]:
		f[i][1]-=1
	f[i][2]=bisect_left(u,pp[i][3])
	if pp[i][2]<pp[i][3]:
		f[i][2]-=1
	f[i][3]=bisect_left(d,-pp[i][2])
	if pp[i][2]<pp[i][3]:
		f[i][3]-=1
	#f[l[i][1]][0]=bisect_left(l,)
co=li()
#print(f)
for i in range(n):
	if 	co==f[i]:
		print(i+1)
		exit(0)
print(-1)
```


864_B. Polycarp and Letters

Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters.

Let A be a set of positions in the string. Let's call it pretty if following conditions are met:

  * letters on positions from A in the string are all distinct and lowercase;
  * there are no uppercase letters in the string which are situated between positions from A (i.e. there is no such j that s[j] is an uppercase letter, and a1 < j < a2 for some a1 and a2 from A).

Write a program that will determine the maximum number of elements in a pretty set of positions.

Input

The first line contains a single integer n (1 ≤ n ≤ 200) — length of string s.

The second line contains a string s consisting of lowercase and uppercase Latin letters.

Output

Print maximum number of elements in pretty set of positions for string s.

Examples

Input

11
aaaaBaabAbA

Output

2

Input

12
zACaAbbaazzC

Output

3

Input

3
ABC

Output

0

Note

In the first example the desired positions might be 6 and 8 or 7 and 8. Positions 6 and 7 contain letters 'a', position 8 contains letter 'b'. The pair of positions 1 and 8 is not suitable because there is an uppercase letter 'B' between these position.

In the second example desired positions can be 7, 8 and 11. There are other ways to choose pretty set consisting of three elements.

In the third example the given string s does not contain any lowercase letters, so the answer is 0.

```python
import re

input()
print(max(map(lambda s: len(set(s)), re.split('[A-Z]', input()))))
```


88_A. Chord

Vasya studies music.

He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note after the H similar and we will identify them with each other. The distance between the notes along the musical scale is measured in tones: between two consecutive notes there's exactly one semitone, that is, 0.5 tone. The distance is taken from the lowest tone to the uppest one, that is, the distance between C and E is 4 semitones and between E and C is 8 semitones

Vasya also knows what a chord is. A chord is an unordered set of no less than three notes. However, for now Vasya only works with triads, that is with the chords that consist of exactly three notes. He can already distinguish between two types of triads — major and minor.

Let's define a major triad. Let the triad consist of notes X, Y and Z. If we can order the notes so as the distance along the musical scale between X and Y equals 4 semitones and the distance between Y and Z is 3 semitones, then the triad is major. The distance between X and Z, accordingly, equals 7 semitones.

A minor triad is different in that the distance between X and Y should be 3 semitones and between Y and Z — 4 semitones.

For example, the triad "C E G" is major: between C and E are 4 semitones, and between E and G are 3 semitones. And the triplet "C# B F" is minor, because if we order the notes as "B C# F", than between B and C# will be 3 semitones, and between C# and F — 4 semitones.

Help Vasya classify the triad the teacher has given to him.

Input

The only line contains 3 space-separated notes in the above-given notation.

Output

Print "major" if the chord is major, "minor" if it is minor, and "strange" if the teacher gave Vasya some weird chord which is neither major nor minor. Vasya promises you that the answer will always be unambiguous. That is, there are no chords that are both major and minor simultaneously.

Examples

Input

C E G

Output

major

Input

C# B F

Output

minor

Input

A B H

Output

strange

```python
# Problem: 88A
# Time Created: August 10(Monday) 2020 || 11:37:58

#>-------------------------<#
import sys

input = sys.stdin.readline
#>-------------------------<#
from itertools import permutations

# Helper Functions. -> Don't cluster your code.
def check_chord(tup):
    notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'B', 'H']
    notes += notes
    x, y, z = tup

    x_y = 0
    y_z = 0

    for i in range(notes.index(x), len(notes)):
        if notes[i] == y: break
        else: x_y += 1
    for i in range(notes.index(y), len(notes)):
        if notes[i] == z: break
        else: y_z += 1

    if x_y == 4 and y_z == 3: return "major"
    elif x_y == 3 and y_z == 4: return "minor"
    else: return "strange"

# IO Functions. -> Input output
def io():
    x, y, z = map(str, input().split())
    perms = permutations([x,y,z])
    return list(perms)

# Main functions. -> Write the main solution here
def solve():
    perms = io()

    ans = 'strange'

    for perm in perms:
        chord = check_chord(perm)
        if chord != 'strange':
            ans = chord
            break
    print(ans)

# Multiple test cases. -> When you have T test cases.
solve()

```


912_D. Fishes

While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size n × m, divided into cells of size 1 × 1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!).

The gift bundle also includes a square scoop of size r × r, designed for fishing. If the lower-left corner of the scoop-net is located at cell (x, y), all fishes inside the square (x, y)...(x + r - 1, y + r - 1) get caught. Note that the scoop-net should lie completely inside the pond when used.

Unfortunately, Sasha is not that skilled in fishing and hence throws the scoop randomly. In order to not frustrate Sasha, Misha decided to release k fishes into the empty pond in such a way that the expected value of the number of caught fishes is as high as possible. Help Misha! In other words, put k fishes in the pond into distinct cells in such a way that when the scoop-net is placed into a random position among (n - r + 1)·(m - r + 1) possible positions, the average number of caught fishes is as high as possible.

Input

The only line contains four integers n, m, r, k (1 ≤ n, m ≤ 105, 1 ≤ r ≤ min(n, m), 1 ≤ k ≤ min(n·m, 105)).

Output

Print a single number — the maximum possible expected number of caught fishes.

You answer is considered correct, is its absolute or relative error does not exceed 10 - 9. Namely, let your answer be a, and the jury's answer be b. Your answer is considered correct, if <image>.

Examples

Input

3 3 2 3

Output

2.0000000000

Input

12 17 9 40

Output

32.8333333333

Note

In the first example you can put the fishes in cells (2, 1), (2, 2), (2, 3). In this case, for any of four possible positions of the scoop-net (highlighted with light green), the number of fishes inside is equal to two, and so is the expected value.

<image>

```python
n, m, r, k = map(int, input().split())

def count(y, x):
    minx = max(0, x-(r-1))
    maxx = min(m-1-(r-1), x)
    miny = max(0, y-(r-1))
    maxy = min(n-1-(r-1), y)
    res = (maxy-miny+1)*(maxx-minx+1)
    return res

#X = [[0]*m for i in range(n)]
#for i in range(n):
    #for j in range(m):
        #X[i][j] = count(i, j)
        #print(i, j, count(i, j))

#for i in range(n):
    #print(*X[i])

sy, sx = n//2, m//2
c = count(sy, sx)
cnt = 0
import heapq
q = [(-c, sy, sx)]
heapq.heapify(q)
visit = set()
visit.add((sy, sx))
E = 0
while q:
    c, y, x = heapq.heappop(q)
    c = -c
    E += c
    cnt += 1
    if cnt == k:
        break
    for dy, dx in (-1, 0), (1, 0), (0, -1), (0, 1):
        ny, nx = y+dy, x+dx
        if 0 <= ny < n and 0 <= nx < m:
            if (ny, nx) in visit:
                continue
            c = count(ny, nx)
            heapq.heappush(q, (-c, ny, nx))
            visit.add((ny, nx))

ans = E/((n-r+1)*(m-r+1))
print(ans)

```


934_D. A Determined Cleanup

In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.

Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...

Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients strictly less than k, whose remainder is p when divided by (x + k). That is, f(x) = q(x)·(x + k) + p, where q(x) is a polynomial (not necessarily with integer coefficients).

Input

The only line of input contains two space-separated integers p and k (1 ≤ p ≤ 1018, 2 ≤ k ≤ 2 000).

Output

If the polynomial does not exist, print a single integer -1, or output two lines otherwise.

In the first line print a non-negative integer d — the number of coefficients in the polynomial.

In the second line print d space-separated integers a0, a1, ..., ad - 1, describing a polynomial <image> fulfilling the given requirements. Your output should satisfy 0 ≤ ai < k for all 0 ≤ i ≤ d - 1, and ad - 1 ≠ 0.

If there are many possible solutions, print any of them.

Examples

Input

46 2

Output

7
0 1 0 0 1 1 1

Input

2018 214

Output

3
92 205 1

Note

In the first example, f(x) = x6 + x5 + x4 + x = (x5 - x4 + 3x3 - 6x2 + 12x - 23)·(x + 2) + 46.

In the second example, f(x) = x2 + 205x + 92 = (x - 9)·(x + 214) + 2018.

```python
p, k = input().split()
p, k = int(p), int(k)
s = k - 1
ls = [0]
while s < p:
    ls.append(0)
    ls.append(0)
    s = s * k * k + k - 1
n = len(ls)
for i in range(n):
    if (i & 1) == 0:
        ls[i] = k - 1
res = s - p
for i in range(n):
    t = res % k
    if i & 1:
        ls[i] += t
    else:
        ls[i] -= t
    res //= k
print(n)
print(" ".join(str(x) for x in ls))

```


988_C. Equal Sums

You are given k sequences of integers. The length of the i-th sequence equals to n_i.

You have to choose exactly two sequences i and j (i ≠ j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the changed sequence j (its length will be equal to n_j - 1).

Note that it's required to remove exactly one element in each of the two chosen sequences.

Assume that the sum of the empty (of the length equals 0) sequence is 0.

Input

The first line contains an integer k (2 ≤ k ≤ 2 ⋅ 10^5) — the number of sequences.

Then k pairs of lines follow, each pair containing a sequence.

The first line in the i-th pair contains one integer n_i (1 ≤ n_i < 2 ⋅ 10^5) — the length of the i-th sequence. The second line of the i-th pair contains a sequence of n_i integers a_{i, 1}, a_{i, 2}, ..., a_{i, n_i}.

The elements of sequences are integer numbers from -10^4 to 10^4.

The sum of lengths of all given sequences don't exceed 2 ⋅ 10^5, i.e. n_1 + n_2 + ... + n_k ≤ 2 ⋅ 10^5.

Output

If it is impossible to choose two sequences such that they satisfy given conditions, print "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), in the second line — two integers i, x (1 ≤ i ≤ k, 1 ≤ x ≤ n_i), in the third line — two integers j, y (1 ≤ j ≤ k, 1 ≤ y ≤ n_j). It means that the sum of the elements of the i-th sequence without the element with index x equals to the sum of the elements of the j-th sequence without the element with index y.

Two chosen sequences must be distinct, i.e. i ≠ j. You can print them in any order.

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

Examples

Input

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

Output

YES
2 6
1 2

Input

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

Output

NO

Input

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

Output

YES
2 2
4 1

Note

In the first example there are two sequences [2, 3, 1, 3, 2] and [1, 1, 2, 2, 2, 1]. You can remove the second element from the first sequence to get [2, 1, 3, 2] and you can remove the sixth element from the second sequence to get [1, 1, 2, 2, 2]. The sums of the both resulting sequences equal to 8, i.e. the sums are equal.

```python
k = int(input())
arr = []
for _ in range(k):
    n = int(input())
    arr.append(list(map(int,input().split())))
d = {}
for i in range(k):
    s = sum(arr[i])
    used = set()
    for j,c in enumerate(arr[i]):
        if c in used:
            continue
        used.add(c)
        if s-c in d:
            print("YES")
            print(*d[s-c])
            print(i+1,j+1)
            exit()
        else:
            d[s-c] = [i+1,j+1]
print("NO")

```


p02595 AtCoder Beginner Contest 174 - Distance

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

* 1 \leq N \leq 2\times 10^5
* 0 \leq D \leq 2\times 10^5
* |X_i|,|Y_i| \leq 2\times 10^5
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Examples

Input

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

Output

3

Input

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Output

7

Input

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Output

6

```python
N, D = map(int, input().split())
P = [tuple(map(int, input().split())) for i in range(N)]

print(sum([p * p + q * q <= D * D for p, q in P]))

```