1227_D2. Optimal Subsequences (Hard Version)

This is the harder version of the problem. In this version, 1 ≤ n, m ≤ 2⋅10^5. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.

You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]:

  * [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list);
  * [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences.

Suppose that an additional non-negative integer k (1 ≤ k ≤ n) is given, then the subsequence is called optimal if:

  * it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k;
  * and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal.

Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 ≤ t ≤ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example:

  * [10, 20, 20] lexicographically less than [10, 21, 1],
  * [7, 99, 99] is lexicographically less than [10, 21, 1],
  * [10, 21, 0] is lexicographically less than [10, 21, 1].

You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.

For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] — it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.

Input

The first line contains an integer n (1 ≤ n ≤ 2⋅10^5) — the length of the sequence a.

The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).

The third line contains an integer m (1 ≤ m ≤ 2⋅10^5) — the number of requests.

The following m lines contain pairs of integers k_j and pos_j (1 ≤ k ≤ n, 1 ≤ pos_j ≤ k_j) — the requests.

Output

Print m integers r_1, r_2, ..., r_m (1 ≤ r_j ≤ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j.

Examples

Input

3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3

Output

20
10
20
10
20
10

Input

7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4

Output

2
3
2
3
2
3
1
1
3

Note

In the first example, for a=[10,20,10] the optimal subsequences are:

  * for k=1: [20],
  * for k=2: [10,20],
  * for k=3: [10,20,10].

```python
"""
    Author - Satwik Tiwari .
    18th Feb , 2021  - Thursday
"""

#===============================================================================================
#importing some useful libraries.

from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key

# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt,log2

from copy import deepcopy
from collections import deque

from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect

#==============================================================================================
#fast I/O region
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

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

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

#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
  def wrapped_func(*args, **kwargs):
    if stack: return f(*args, **kwargs)
    to = f(*args, **kwargs)
    while True:
      if type(to) is GeneratorType:
        stack.append(to)
        to = next(to)
        continue
      stack.pop()
      if not stack: break
      to = stack[-1].send(to)
    return to
  return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
    for pp in range(t):
        solve(pp)
def google(p):
    print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    y%=(p-1)  #not so sure about this. used when y>p-1. if p is prime.
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))

class FenwickTree:
    def __init__(self, x):
        """transform list into BIT"""
        self.bit = x
        for i in range(len(x)):
            j = i | (i + 1)
            if j < len(x):
                x[j] += x[i]

    def update(self, idx, x):
        """updates bit[idx] += x"""
        while idx < len(self.bit):
            self.bit[idx] += x
            idx |= idx + 1

    def query(self, end):
        """calc sum(bit[:end))"""
        x = 0
        while end:
            x += self.bit[end - 1]
            end &= end - 1
        return x

    def findkth(self, k):
        """Find largest idx such that sum(bit[:idx]) <= k"""
        idx = -1
        for d in reversed(range(len(self.bit).bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < len(self.bit) and k >= self.bit[right_idx]:
                idx = right_idx
                k -= self.bit[idx]
        return idx + 1

    def printpref(self):
        out = []
        for i in range(1,len(self.bit) + 1):
            out.append(self.query(i))
        print(out)

"""
    ask query(i+1) ---->>> 1 indexed based
    update(i,x) --->>> 0indexed based
"""

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

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

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

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

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

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

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

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

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

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

    def _loc_left(self, value):
        """Return an index pair that corresponds to the first position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        lo, pos = -1, len(_lists) - 1
        while lo + 1 < pos:
            mi = (lo + pos) >> 1
            if value <= _mins[mi]:
                pos = mi
            else:
                lo = mi

        if pos and value <= _lists[pos - 1][-1]:
            pos -= 1

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value <= _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def _loc_right(self, value):
        """Return an index pair that corresponds to the last position of `value` in the sorted list."""
        if not self._len:
            return 0, 0

        _lists = self._lists
        _mins = self._mins

        pos, hi = 0, len(_lists)
        while pos + 1 < hi:
            mi = (pos + hi) >> 1
            if value < _mins[mi]:
                hi = mi
            else:
                pos = mi

        _list = _lists[pos]
        lo, idx = -1, len(_list)
        while lo + 1 < idx:
            mi = (lo + idx) >> 1
            if value < _list[mi]:
                idx = mi
            else:
                lo = mi

        return pos, idx

    def add(self, value):
        """Add `value` to sorted list."""
        _load = self._load
        _lists = self._lists
        _mins = self._mins
        _list_lens = self._list_lens

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

    def discard(self, value):
        """Remove `value` from sorted list if it is a member."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_right(value)
            if idx and _lists[pos][idx - 1] == value:
                self._delete(pos, idx - 1)

    def remove(self, value):
        """Remove `value` from sorted list; `value` must be a member."""
        _len = self._len
        self.discard(value)
        if _len == self._len:
            raise ValueError('{0!r} not in list'.format(value))

    def pop(self, index=-1):
        """Remove and return value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        value = self._lists[pos][idx]
        self._delete(pos, idx)
        return value

    def bisect_left(self, value):
        """Return the first index to insert `value` in the sorted list."""
        pos, idx = self._loc_left(value)
        return self._fen_query(pos) + idx

    def bisect_right(self, value):
        """Return the last index to insert `value` in the sorted list."""
        pos, idx = self._loc_right(value)
        return self._fen_query(pos) + idx

    def count(self, value):
        """Return number of occurrences of `value` in the sorted list."""
        return self.bisect_right(value) - self.bisect_left(value)

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

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

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

    def __contains__(self, value):
        """Return true if `value` is an element of the sorted list."""
        _lists = self._lists
        if _lists:
            pos, idx = self._loc_left(value)
            return idx < len(_lists[pos]) and _lists[pos][idx] == value
        return False

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

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

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

def solve(case):
    n = int(inp())
    a = lis()

    queries = []
    m = int(inp())
    for i in range(m):
        k,pos = sep()
        queries.append((k,pos,i))

    queries.sort()
    b = sorted(a)[::-1]

    ind = {}
    for i in range(n):
        if(a[i] not in ind):
            ind[a[i]] = deque([i])
        else:
            ind[a[i]].append(i)

    # currind = 0
    # bit = FenwickTree([0]*(len(a) + 10))
    # ans = [-1]*m
    # for k,pos,where in queries:
    #     while(currind < k):
    #         print(b[currind],'========')
    #         bit.update(ind[b[currind]].popleft(),1)
    #         currind+=1
    #     print(where,'==',bit.findkth(pos-1),pos)
    #     ans[where] = (bit.findkth(pos-1) + 1)
    #     print(bit.printpref())
    #
    # for i in ans:
    #     print(a[i])
    sl = SortedList()
    currind = 0
    ans = [-1]*m
    for k,pos,where in queries:
        while(currind < k):
            sl.add(ind[b[currind]].popleft())
            currind += 1
        ans[where] = a[sl[pos-1]]

    for i in ans:
        print(i)

testcase(1)
# testcase(int(inp()))

```


126_A. Hot Bath

Bob is about to take a hot bath.

There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can transmit from 0 to x2 water units per second.

If y1 water units per second flow through the first tap and y2 water units per second flow through the second tap, then the resulting bath water temperature will be:

<image>

Bob wants to open both taps so that the bath water temperature was not less than t0. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible.

Determine how much each tap should be opened so that Bob was pleased with the result in the end.

Input

You are given five integers t1, t2, x1, x2 and t0 (1 ≤ t1 ≤ t0 ≤ t2 ≤ 106, 1 ≤ x1, x2 ≤ 106).

Output

Print two space-separated integers y1 and y2 (0 ≤ y1 ≤ x1, 0 ≤ y2 ≤ x2).

Examples

Input

10 70 100 100 25

Output

99 33

Input

300 500 1000 1000 300

Output

1000 0

Input

143 456 110 117 273

Output

76 54

Note

In the second sample the hot water tap shouldn't be opened, but the cold water tap should be opened at full capacity in order to fill the bath in the quickest way possible.

```python
import math
def gcd(a,b):
    if(b==0):
        return a
    return gcd(b,a%b)
l=input().split()
t1=int(l[0])
t2=int(l[1])
x1=int(l[2])
x2=int(l[3])
t0=int(l[4])
num1=t2-t0
num2=t0-t1
if(t1==t2):
    print(x1,x2)
    quit()
if(num1==0):
    print(0,x2)
    quit()
if(num2==0):
    print(x1,0)
    quit()
z=num2/num1
maxa=10**18
ans=(0,0)
for i in range(1,x1+1):
    ok=z*i
    if(ok>x2):
        break
    num1=i
    num2=math.ceil(ok)
    if(maxa==((num2/num1)-z) and num2+num1>ans[0]+ans[1]):
        ans=(num1,num2)
    elif(maxa>((num2/num1)-z)):
        ans=(num1,num2)
        maxa=((num2/num1-z))
if(ans==(0,0)):
    ans=(0,x2)
print(ans[0],ans[1])

```


1312_A. Two Regular Polygons

You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length).

<image> Examples of convex regular polygons

Your task is to say if it is possible to build another convex regular polygon with m vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.

You have to answer t independent test cases.

Input

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

The next t lines describe test cases. Each test case is given as two space-separated integers n and m (3 ≤ m < n ≤ 100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.

Output

For each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with m vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.

Example

Input

2
6 3
7 3

Output

YES
NO

Note

<image> The first test case of the example

It can be shown that the answer for the second test case of the example is "NO".

```python
for i in range(int(input())):
    a,b=input().split()
    if int(b)<=2:
        print("NO")
    elif int(a)%int(b)==0:
        print("YES")
    else:
        print("NO")
```


1334_E. Divisor Paths

You are given a positive integer D. Let's build the following graph from it:

  * each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included);
  * two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime;
  * the weight of an edge is the number of divisors of x that are not divisors of y.

For example, here is the graph for D=12:

<image>

Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].

There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime.

Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.

So the shortest path between two vertices v and u is the path that has the minimal possible length.

Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.

You are given q queries of the following form:

  * v u — calculate the number of the shortest paths between vertices v and u.

The answer for each query might be large so print it modulo 998244353.

Input

The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from.

The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries.

Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).

Output

Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.

Examples

Input

12
3
4 4
12 1
3 4

Output

1
3
1

Input

1
1
1 1

Output

1

Input

288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325

Output

547558588
277147129
457421435
702277623

Note

In the first example:

  * The first query is only the empty path — length 0;
  * The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5).
  * The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).

```python
import sys
input = sys.stdin.buffer.readline
mod=998244353
d=int(input())
div=[]
x=2
di=0
t=0
while d>1 and x*x<=d:
    if d%x==0:
        div.append(x)
        d//=x
        di+=1
        t+=1
    while d%x==0:
        d//=x
        t+=1
    x+=1
if d>1:
    div.append(d)
    di+=1
    t+=1
fac=[1]
for i in range(1,t+1):
    fac.append(i*fac[-1]%mod)
for f in range(int(input())):
    v,u=map(int,input().split())
    divs1=[]
    divs2=[]
    tot1=0
    tot2=0
    for i in range(di):
        while v%div[i]==0 and u%div[i]==0:
            v//=div[i]
            u//=div[i]
        if v%div[i]==0:
            divs1.append(0)
        if u%div[i]==0:
            divs2.append(0)
        while v%div[i]==0:
            v//=div[i]
            divs1[-1]+=1
            tot1+=1
        while u%div[i]==0:
            u//=div[i]
            divs2[-1]+=1
            tot2+=1
    res=fac[tot1]*fac[tot2]
    tod=1
    for x in divs1:
        tod*=fac[x]
        tod%=mod
    for x in divs2:
        tod*=fac[x]
        tod%=mod
    res*=pow(tod,mod-2,mod)
    res%=mod
    print(res)
```


1354_G. Find a Gift

This is an interactive problem. Don't forget to flush output after printing queries using cout.flush() or fflush(stdout) in C++ or similar functions in other programming languages.

There are n gift boxes in a row, numbered from 1 to n from left to right. It's known that exactly k of them contain valuable gifts — other boxes contain just lucky stones. All boxes look the same and differ only in weight. All boxes with stones have the same weight and are strictly heavier than boxes with valuable items. But valuable gifts may be different, so the boxes with valuable items may have different weights.

You can ask no more than 50 queries (printing an answer doesn't count). By each query you can compare total weights of two non-intersecting subsets of boxes a_1, a_2, ..., a_{k_a} and b_1, b_2, ..., b_{k_b}. In return you'll get one of four results:

  * FIRST, if subset a_1, a_2, ..., a_{k_a} is strictly heavier;
  * SECOND, if subset b_1, b_2, ..., b_{k_b} is strictly heavier;
  * EQUAL, if subsets have equal total weights;
  * WASTED, if the query is incorrect or the limit of queries is exceeded.

Using such queries (or, maybe, intuition) find the box with a valuable gift with the minimum index.

Input

The input consists of several cases. In the beginning, you receive the integer T (1 ≤ T ≤ 500) — the number of test cases.

At the beginning of each test case, you receive two integers n and k (2 ≤ n ≤ 1000, 1 ≤ k ≤ n/2) — the number of boxes in a row and the number of boxes with valuable gifts.

It's guaranteed that the order of boxes is fixed beforehand and that the sum of n in one test doesn't exceed 1000.

Output

For each test case print the minimum index among all boxes with a valuable gift in the following format: "! x" where x (1 ≤ x ≤ n) — the index of the box.

Interaction

Print each query in three lines. In the first line print the sizes of subset in the following format: "? k_a k_b" where k_a and k_b (1 ≤ k_a, k_b ≤ n; k_a + k_b ≤ n) — the corresponding sizes.

In the second line print k_a integers a_1, a_2, ..., a_{k_a} (1 ≤ a_i ≤ n; a_i ≠ a_j if i ≠ j) — indexes of boxes in the first subset.

In the third line print k_b integers b_1, b_2, ..., b_{k_b} (1 ≤ b_i ≤ n; b_i ≠ b_j if i ≠ j) — indexes of boxes in the second subset.

The subsets shouldn't intersect, i. e. a_i ≠ b_j for all i and j.

You'll receive one of four responses described above. In the case of WASTED stop your program to avoid getting random verdict instead of Wrong Answer.

Example

Input

2
2 1
-
-
-
FIRST
-
5 2
-
-
-
FIRST
-
-
-
SECOND
-
-
-
EQUAL
-

Output

-
-
? 1 1
1
2
-
! 2
-
? 1 1
1
2
-
? 2 3
4 2
1 3 5
-
? 1 1
4
5
-
! 1

Note

Additional separators "–" in the sample are used only to increase the readability of the sample. Don't print any unnecessary symbols or line breaks in your solution when you send it to the system.

Hacks are forbidden in this task.

```python
from random import randint
def ask(l1, r1, l2, r2):
	print('?', r1 - l1 + 1, r2 - l2 + 1)
	for i in range(l1, r1 + 1):
		print(i + 1, end=' ')
	print()
	for i in range(l2, r2 + 1):
		print(i + 1, end=' ')
	print(flush=True)
	s = input()
	if s[0] == 'F':
		return 0
	if s[0] == 'S':
		return 1
	if s[0] == 'E':
		return 2
	exit()
for _ in range(int(input())):
	n, k = map(int, input().split())
	flag = 0
	for i in range(30):
		x = randint(1, n - 1)
		if ask(0, 0, x, x) == 1:
			print('!', 1)
			flag = 1
			break
	if flag:
		continue
	i = 0
	while ask(0, (1 << i) - 1, 1 << i, min(n - 1, (1 << i + 1) - 1)) == 2:
		i += 1
	l, r = 0, min(n - (1 << i) - 1, (1 << i) - 1)
	while l < r:
		m = l + r >> 1
		if ask(0, m, 1 << i, (1 << i) + m) == 2:
			l = m + 1
		else:
			r = m
	print('!', (1 << i) + l + 1)

```


1374_E2. Reading Books (hard version)

Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.

Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read exactly m books before all entertainments. Alice and Bob will read each book together to end this exercise faster.

There are n books in the family library. The i-th book is described by three integers: t_i — the amount of time Alice and Bob need to spend to read it, a_i (equals 1 if Alice likes the i-th book and 0 if not), and b_i (equals 1 if Bob likes the i-th book and 0 if not).

So they need to choose exactly m books from the given n books in such a way that:

  * Alice likes at least k books from the chosen set and Bob likes at least k books from the chosen set;
  * the total reading time of these m books is minimized (they are children and want to play and joy as soon a possible).

The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of t_i over all books that are in the chosen set.

Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.

Input

The first line of the input contains three integers n, m and k (1 ≤ k ≤ m ≤ n ≤ 2 ⋅ 10^5).

The next n lines contain descriptions of books, one description per line: the i-th line contains three integers t_i, a_i and b_i (1 ≤ t_i ≤ 10^4, 0 ≤ a_i, b_i ≤ 1), where:

  * t_i — the amount of time required for reading the i-th book;
  * a_i equals 1 if Alice likes the i-th book and 0 otherwise;
  * b_i equals 1 if Bob likes the i-th book and 0 otherwise.

Output

If there is no solution, print only one integer -1.

If the solution exists, print T in the first line — the minimum total reading time of the suitable set of books. In the second line print m distinct integers from 1 to n in any order — indices of books which are in the set you found.

If there are several answers, print any of them.

Examples

Input

6 3 1
6 0 0
11 1 0
9 0 1
21 1 1
10 1 0
8 0 1

Output

24
6 5 1

Input

6 3 2
6 0 0
11 1 0
9 0 1
21 1 1
10 1 0
8 0 1

Output

39
4 6 5

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

INF = 10 ** 18
n, m, k = map(int, input().split())
B = sorted((tuple(map(int, input().split())) + (i,) for i in range(n)), key=lambda v: v[0])

GB, AB, BB, RB = ([] for _ in range(4))

for t, a, b, i in B:
	if a and b: GB.append((t, i))
	elif a: AB.append((t, i))
	elif b: BB.append((t, i))
	else: RB.append((t, i))

N = 1
while N <= 10 ** 4: N *= 2

T = [(0, 0)] * (2 * N)
def comb(a, b): return (a[0] + b[0], a[1] + b[1])

def add_book(t, inc=1):
	i = t + N
	T[i] = comb(T[i], (t*inc, inc))
	while i > 1:
		i //= 2
		T[i] = comb(T[i*2], T[i*2+1])

def query(x):
	assert x >= 0
	s = 0
	i = 1
	while x:
		ts, tc = T[i]
		if tc < x: return INF
		elif tc == x:
			s += ts
			break

		if i >= N:
			s += ts // tc * x
			break

		i *= 2
		if T[i][1] < x:
			s += T[i][0]
			x -= T[i][1]
			i += 1
	return s

gb_i = 0
gb_t = 0
while gb_i < min(len(GB), m):
	gb_t += GB[gb_i][0]
	gb_i += 1

cb_i = 0
cb_t = 0
while gb_i + cb_i < k and gb_i + 2 * (cb_i + 1) <= m and cb_i < min(len(AB), len(BB)):
	cb_t += AB[cb_i][0] + BB[cb_i][0]
	cb_i += 1

for t, _ in GB[gb_i:]: add_book(t)
for t, _ in AB[cb_i:]: add_book(t)
for t, _ in BB[cb_i:]: add_book(t)
for t, _ in RB: add_book(t)

if gb_i + cb_i < k:
	print(-1)
	sys.exit()

best = (INF, -1, -1)
while True:
	best = min(best, (gb_t + cb_t + query(m - 2 * cb_i - gb_i), gb_i, cb_i))

	if not gb_i: break

	gb_i -= 1
	gb_t -= GB[gb_i][0]
	add_book(GB[gb_i][0])

	if gb_i + cb_i < k:
		if cb_i == min(len(AB), len(BB)): break

		cb_t += AB[cb_i][0] + BB[cb_i][0]
		add_book(AB[cb_i][0], -1)
		add_book(BB[cb_i][0], -1)
		cb_i += 1

		if gb_i + 2 * cb_i > m: break

bs, bi, bj = best
assert bs != INF

ans = []
comps = 0
for t, i in GB[:bi]:
	ans.append(i+1)
	comps += t

for t, i in AB[:bj]:
	ans.append(i+1)
	comps += t
for t, i in BB[:bj]:
	ans.append(i+1)
	comps += t

if bi + 2 * bj < m:
	rem = GB[bi:] + AB[bj:] + BB[bj:] + RB
	rem.sort()
	for t, i in rem[:m - bi - 2 * bj]:
		ans.append(i+1)
		comps += t

assert comps == bs
print(bs)
print(*ans)

```


1398_B. Substring Removal Game

Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on.

During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them.

For example, if the string is 10110, there are 6 possible moves (deleted characters are bold):

  1. 10110 → 0110;
  2. 10110 → 1110;
  3. 10110 → 1010;
  4. 10110 → 1010;
  5. 10110 → 100;
  6. 10110 → 1011.

After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: 10110 → 100 → 1.

The game ends when the string becomes empty, and the score of each player is the number of 1-characters deleted by them.

Each player wants to maximize their score. Calculate the resulting score of Alice.

Input

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

Each test case contains exactly one line containing a binary string s (1 ≤ |s| ≤ 100).

Output

For each test case, print one integer — the resulting score of Alice (the number of 1-characters deleted by her).

Example

Input

5
01111001
0000
111111
101010101
011011110111

Output

4
0
6
3
6

Note

Questions about the optimal strategy will be ignored.

```python
for i in range(int(input())):
    s = list(filter(lambda x:x !='',input().split('0')))
    s.sort(reverse=True)
    pr = ''
    for i in range(0,len(s),2):
        pr +=s[i]
    print(len(pr))

```


1421_C. Palindromifier

Ringo found a string s of length n in his [yellow submarine](https://www.youtube.com/watch?v=m2uTFF_3MaA). The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string s into a palindrome by applying two types of operations to the string.

The first operation allows him to choose i (2 ≤ i ≤ n-1) and to append the substring s_2s_3 … s_i (i - 1 characters) reversed to the front of s.

The second operation allows him to choose i (2 ≤ i ≤ n-1) and to append the substring s_i s_{i + 1}… s_{n - 1} (n - i characters) reversed to the end of s.

Note that characters in the string in this problem are indexed from 1.

For example suppose s=abcdef. If he performs the first operation with i=3 then he appends cb to the front of s and the result will be cbabcdef. Performing the second operation on the resulted string with i=5 will yield cbabcdefedc.

Your task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) at most 30 times. The length of the resulting palindrome must not exceed 10^6

It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.

Input

The only line contains the string S (3 ≤ |s| ≤ 10^5) of lowercase letters from the English alphabet.

Output

The first line should contain k (0≤ k ≤ 30) — the number of operations performed.

Each of the following k lines should describe an operation in form L i or R i. L represents the first operation, R represents the second operation, i represents the index chosen.

The length of the resulting palindrome must not exceed 10^6.

Examples

Input

abac

Output

2
R 2
R 5

Input

acccc

Output

2
L 4
L 2

Input

hannah

Output

0

Note

For the first example the following operations are performed:

abac → abacab → abacaba

The second sample performs the following operations: acccc → cccacccc → ccccacccc

The third example is already a palindrome so no operations are required.

```python
s=input()
n= len(s)
print(4)
print("L",2)
print("R",n)
print("R",2)
print("R",2*n+1)

```


143_B. Help Kingdom of Far Far Away 2

For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to 0.01, and not up to an integer.

The King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows:

  * A number contains the integer part and the fractional part. The two parts are separated with a character "." (decimal point).
  * To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character "," (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678
  * In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply discarded (they are not rounded: see sample tests).
  * When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets.
  * Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency — snakes ($), that's why right before the number in the financial format we should put the sign "$". If the number should be written in the brackets, then the snake sign should also be inside the brackets.

For example, by the above given rules number 2012 will be stored in the financial format as "$2,012.00" and number -12345678.9 will be stored as "($12,345,678.90)".

The merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?

Input

The input contains a number that needs to be converted into financial format. The number's notation length does not exceed 100 characters, including (possible) signs "-" (minus) and "." (decimal point). The number's notation is correct, that is:

  * The number's notation only contains characters from the set {"0" – "9", "-", "."}.
  * The decimal point (if it is present) is unique and is preceded and followed by a non-zero quantity on decimal digits
  * A number cannot start with digit 0, except for a case when its whole integer part equals zero (in this case the integer parts is guaranteed to be a single zero: "0").
  * The minus sign (if it is present) is unique and stands in the very beginning of the number's notation
  * If a number is identically equal to 0 (that is, if it is written as, for example, "0" or "0.000"), than it is not preceded by the minus sign.
  * The input data contains no spaces.
  * The number's notation contains at least one decimal digit.

Output

Print the number given in the input in the financial format by the rules described in the problem statement.

Examples

Input

2012

Output

$2,012.00

Input

0.000

Output

$0.00

Input

-0.00987654321

Output

($0.00)

Input

-12345678.9

Output

($12,345,678.90)

Note

Pay attention to the second and third sample tests. They show that the sign of a number in the financial format (and consequently, the presence or absence of brackets) is determined solely by the sign of the initial number. It does not depend on the sign of the number you got after translating the number to the financial format.

```python
import math
import sys
import collections

# imgur.com/Pkt7iIf.png

def getdict(n):
    d = {}
    if type(n) is list:
        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 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)

s = input()
t = s.split('.') if '.' in s else [s, '']
a, b = t[0], t[1]
b += '00'
neg = False
if a[0] == '-':
    neg = True
    a = a[1:]
r = []
for i in range(len(a), 0, -3):
    r.append(a[max(0, i-3):i])
r.reverse()
res = ','.join(r) + '.' + b[0:2]
print(f'(${res})') if neg else print(f'${res}')
```


1491_A. K-th Largest Value

You are given an array a consisting of n integers. Initially all elements of a are either 0 or 1. You need to process q queries of two kinds:

  * 1 x : Assign to a_x the value 1 - a_x.
  * 2 k : Print the k-th largest value of the array.

As a reminder, k-th largest value of the array b is defined as following:

  * Sort the array in the non-increasing order, return k-th element from it.

For example, the second largest element in array [0, 1, 0, 1] is 1, as after sorting in non-increasing order it becomes [1, 1, 0, 0], and the second element in this array is equal to 1.

Input

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

The second line contains n integers a_1, a_2, a_3, ..., a_n (0 ≤ a_i ≤ 1) — elements of the initial array.

Each of the following q lines contains two integers. The first integer is t (1 ≤ t ≤ 2) — the type of query.

  * If t = 1 the second integer is x (1 ≤ x ≤ n) — the position of the modified number. You have to assign to a_x the value 1 - a_x.
  * If t = 2 the second integer is k (1 ≤ k ≤ n) — you need to print the k-th largest value of the array.

It's guaranteed that there will be at least one query of the second type (satisfying t = 2).

Output

For each query of the second type, print a single integer — the answer to the query.

Example

Input

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

Output

1
0
1
0

Note

Initially a = [1, 1, 0, 1, 0].

The first operation is printing the third largest value, which is 1.

The second operation is assigning a_2 the value 0, a becomes [1, 0, 0, 1, 0].

The third operation is printing the third largest value, it is 0.

The fourth operation is printing the first largest value, it is 1.

The last operation is printing the fifth largest value, it is 0.

```python
n, q = map(int,input().split())
a = list(map(int,input().split()))
zero = a.count(0)
one = n - zero
for _ in range(q):
    t, x = map(int,input().split())
    if t == 1:
        if a[x-1] == 1:
            zero += 1
            one -= 1
            a[x-1] = 0
        else:
            zero -= 1
            one += 1
            a[x-1] = 1
    else:
        if x<=one:
            print(1)
        else:
            print(0)

```


1513_D. GCD and MST

You are given an array a of n (n ≥ 2) positive integers and an integer p. Consider an undirected weighted graph of n vertices numbered from 1 to n for which the edges between the vertices i and j (i<j) are added in the following manner:

  * If gcd(a_i, a_{i+1}, a_{i+2}, ..., a_{j}) = min(a_i, a_{i+1}, a_{i+2}, ..., a_j), then there is an edge of weight min(a_i, a_{i+1}, a_{i+2}, ..., a_j) between i and j.
  * If i+1=j, then there is an edge of weight p between i and j.

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

Note that there could be multiple edges between i and j if both of the above conditions are true, and if both the conditions fail for i and j, then there is no edge between these vertices.

The goal is to find the weight of the [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) of this graph.

Input

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

The first line of each test case contains two integers n (2 ≤ n ≤ 2 ⋅ 10^5) and p (1 ≤ p ≤ 10^9) — the number of nodes and the parameter p.

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

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

Output

Output t lines. For each test case print the weight of the corresponding graph.

Example

Input

4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15

Output

5
3
12
46

Note

Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):

For test case 1

<image>

For test case 2

<image>

For test case 3

<image>

For test case 4

<image>

```python

class UnionFind:
    def __init__(self, n):
        self.Id = list(range(n+1))
        self.sz = [1]*(n+1)

    def find(self, node):
        root = node
        while root != self.Id[root]:
            root = self.Id[root]
        while node != root:
            nxt = self.Id[node]
            self.Id[node] = root
            node = nxt
        return root

    def union(self, u, v):
        pu, pv = self.find(u), self.find(v)
        if pu==pv:
            return False
        if self.sz[pu] <= self.sz[pv]:
            self.Id[pu] = pv
            self.sz[pv] += self.sz[pu]
        else:
            self.Id[pv] = pu
            self.sz[pu] += self.sz[pv]
        return True

def solve(A, n, p):
    edg = []
    for i in range(1, n):
        edg.append((p, i, i+1))
    pel, pind = 10**9 + 10, 1
    for i,it in enumerate(A):
        if it % pel == 0:
            edg.append((pel, pind, i+1))
        else:
            pel, pind = it, i+1
    pel, pind = 10**9 + 10, n
    i = n
    for it in A[-1::-1]:
        if it % pel == 0:
            edg.append((pel, i, pind))
        else:
            pel, pind = it, i
        i-=1

    ## minimum spanning tree
    edg.sort()
    dsu = UnionFind(n)
    ans = 0
    for w, u, v in edg:
        if dsu.union(u, v):
            ans += w
    return ans
for case in range(int(input())):
    n, p = map(int, input().split())
    A = list(map(int,input().split()))
    ans = solve(A, n, p)
    print(ans)

```


1540_C2. Converging Array (Hard Version)

This is the hard version of the problem. The only difference is that in this version 1 ≤ q ≤ 10^5. You can make hacks only if both versions of the problem are solved.

There is a process that takes place on arrays a and b of length n and length n-1 respectively.

The process is an infinite sequence of operations. Each operation is as follows:

  * First, choose a random integer i (1 ≤ i ≤ n-1).
  * Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).

See notes for an example of an operation.

It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.

You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 ≤ a_i ≤ c_i for 1 ≤ i ≤ n.

Your task is to count the number of good arrays a where F(a, b) ≥ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.

Input

The first line contains a single integer n (2 ≤ n ≤ 100).

The second line contains n integers c_1, c_2 …, c_n (0 ≤ c_i ≤ 100).

The third line contains n-1 integers b_1, b_2, …, b_{n-1} (0 ≤ b_i ≤ 100).

The fourth line contains a single integer q (1 ≤ q ≤ 10^5).

The fifth line contains q space separated integers x_1, x_2, …, x_q (-10^5 ≤ x_i ≤ 10^5).

Output

Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) ≥ x_i modulo 10^9+7.

Example

Input

3
2 3 4
2 1
5
-1 0 1 -100000 100000

Output

56
28
4
60
0

Note

The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).

Examples of arrays a that are not good:

  * a = [3, 2, 3] is not good because a_1 > c_1;
  * a = [0, -1, 3] is not good because a_2 < 0.

One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.

Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2.

```python
def solve():
    MOD = 10**9+7
    n = int(input())
    c = list(map(int, input().split()))
    b = [0] + list(map(int, input().split()))
    q = int(input())
    queries = list(map(int, input().split()))
    maxans = 1
    for c1 in c:
        maxans = maxans * (c1+1) % MOD
    ans = {}
    for i in range(1, n):
        b[i] += b[i-1]
    s = lb = 0
    for i in range(1, n):
        s -= b[i]
        lb = min(lb, s//(i+1))
    s = ub = c[0]
    for i in range(n):
        s += c[i] - b[i]
        ub = min(ub, s//(i+1))
    for x in queries:
        if x <= lb:
            print(maxans)
        elif x > ub:
            print(0)
        elif x in ans:
            print(ans[x])
        else:
            dp0 = [1] * 10002
            dp0[0] = 0
            bd = 0
            for i in range(n):
                dp1 = [0] * 10002
                bd += b[i] + x
                for j in range(max(bd, 0), 10001):
                    dp1[j+1] = (dp1[j] + dp0[j+1] - dp0[max(j-c[i], 0)]) % MOD
                dp0 = dp1[:]
            a = dp0[-1]
            ans[x] = a
            print(a)

import sys
input = lambda: sys.stdin.readline().rstrip()
solve()

```


168_B. Wizards and Minimal Spell

Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells.

Each spell consists of several lines. The line, whose first non-space character is character "#" is an amplifying line and it is responsible for spell power. The remaining lines are common, and determine the effect of the spell.

You came across the text of some spell. Spell was too long, so you cannot understand its meaning. So you want to make it as short as possible without changing the meaning.

The only way to shorten a spell that you know is the removal of some spaces and line breaks. We know that when it comes to texts of spells, the spaces carry meaning only in the amplifying lines, so we should remove all spaces in other lines. Newlines also do not matter, unless any of the two separated lines is amplifying. Thus, if two consecutive lines are not amplifying, they need to be joined into one (i.e. we should concatenate the second line to the first one). Removing spaces in amplifying lines and concatenating the amplifying lines to anything is forbidden.

Note that empty lines must be processed just like all the others: they must be joined to the adjacent non-amplifying lines, or preserved in the output, if they are surrounded with amplifying lines on both sides (i.e. the line above it, if there is one, is amplifying, and the line below it, if there is one, is amplifying too).

For now those are the only instructions for removing unnecessary characters that you have to follow (oh yes, a newline is a character, too).

The input contains the text of the spell, which should be reduced. Remove the extra characters and print the result to the output.

Input

The input contains multiple lines. All characters in the lines have codes from 32 to 127 (inclusive). Please note that the lines may begin with or end with one or more spaces. The size of the input does not exceed 1048576 ( = 220) bytes. Newlines are included in this size.

In the Windows operating system used on the testing computer, a newline is a sequence of characters with codes #13#10. It is guaranteed that after each line of input there is a newline. In particular, the input ends with a newline. Note that the newline is the end of the line, and not the beginning of the next one.

It is guaranteed that the input contains at least one character other than a newline.

It is recommended to organize the input-output line by line, in this case the newlines will be processed correctly by the language means.

Output

Print the text of the spell where all extra characters are deleted. Please note that each output line should be followed by a newline.

Please be careful: your answers will be validated by comparing them to the jury's answer byte-by-byte. So, all spaces and newlines matter.

Examples

Input

   #   include <cstdio>

using namespace std;

int main     (   ){
puts("Hello # World"); #
#
}

Output

   #   include <cstdio>
usingnamespacestd;intmain(){puts("Hello#World");#
#
}

Input

#

#

Output

#

#

Note

In the first sample the amplifying lines are lines 1 and 7. So, lines 2 to 6 are concatenated to each other, all spaces are deleted from them.

In the second sample the amplifying lines are lines 1 and 3. So, no lines are concatenated to each other.

```python
v = []
c = []
resp = ""

while True:
	try:
		v.append(input())
	except:
		break

i = 0
while i < len(v):
	k = v[i].replace(" ","")
	if(k == ""):
		v[i] = k
		c.append(False)
	elif(k[0] == '#'):
		c.append(True)
	else:
		v[i] = k
		c.append(False)
	i+=1

n = len(v)
i = 0
while i < n - 1:
	if(not c[i] and not c[i+1]):
		resp += v[i]
	else:
		resp += v[i] + "\n"
	i += 1
resp += v[i]

print(resp)
```


20_C. Dijkstra?

You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.

Input

The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.

It is possible that the graph has loops and multiple edges between pair of vertices.

Output

Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.

Examples

Input

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

Output

1 4 3 5

Input

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

Output

1 4 3 5

```python

from collections import defaultdict
from heapq import heappush, heapify, heappop

INF = 10 ** 18
class Graph:
	def __init__(self):
		self.adj_list = defaultdict(list)

	def add_edge(self, src, dest, cost):
		self.adj_list[src].append((dest, cost))
		self.adj_list[dest].append((src, cost))

def dijkstra(graph, src, dest, n):
	dist = [INF] * n
	vis = [False] * n
	dist[src] = 0
	min_queue = [(0, src)]
	heapify(min_queue)
	parent = [-1] * n

	while min_queue:
		d, u = heappop(min_queue)
		if vis[u]:
			continue
		vis[u] = True
		for v, d2 in graph.adj_list[u]:
			if d2 + d < dist[v]:
				dist[v] = d2 + d
				heappush(min_queue, (dist[v], v))
				parent[v] = u

	if dist[dest] == INF:
		return "-1"
	path = []
	curr = dest
	while curr != -1:
		path.append(curr + 1)
		curr = parent[curr]
	path.reverse()
	return " ".join(str(i) for i in path)

def main():
    graph = Graph()

    n, m = [int(i) for i in input().split()]
    for i in range(m):
        u, v, w = [int(j) for j in input().split()]
        u -= 1
        v -= 1
        graph.add_edge(u, v, w)

    print(dijkstra(graph, 0, n - 1, n))

if __name__ == '__main__':
    main()

```


235_E. Number Challenge

Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum:

<image>

Find the sum modulo 1073741824 (230).

Input

The first line contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 2000).

Output

Print a single integer — the required sum modulo 1073741824 (230).

Examples

Input

2 2 2

Output

20

Input

4 4 4

Output

328

Input

10 10 10

Output

11536

Note

For the first example.

  * d(1·1·1) = d(1) = 1;
  * d(1·1·2) = d(2) = 2;
  * d(1·2·1) = d(2) = 2;
  * d(1·2·2) = d(4) = 3;
  * d(2·1·1) = d(2) = 2;
  * d(2·1·2) = d(4) = 3;
  * d(2·2·1) = d(4) = 3;
  * d(2·2·2) = d(8) = 4.

So the result is 1 + 2 + 2 + 3 + 2 + 3 + 3 + 4 = 20.

```python
primes = []
d = {}
for i in range(2, 100):
    if i not in d:
        primes.append(i)
        j = 2
        while i * j < 100:
            d[i*j] = 1
            j += 1

def solve(x,y,z):
    d = {}
    for p in primes:
        d[p] = 0

    for p in primes:
        if p > x and p > y and p > z:
            break
        while x%p == 0:
            x /= p
            d[p] += 1
        while y%p == 0:
            y /= p
            d[p] += 1
        while z%p == 0:
            z /= p
            d[p] += 1
    ans = 1
    for p in primes:
        ans *= d[p] + 1
    return ans

a,b,c = map(int,input().split(' '))
ans = 0
seen = {}

for i in range(1, a+1):
    for j in range(1, b+1):
        for k in range(1, c+1):
            p = i*j*k
            if p in seen:
                ans = (ans + seen[p]) % 1073741824
            else:
                temp = solve(i,j,k)
                ans = (ans + temp) % 1073741824
                seen[p] = temp

print(ans)

```


260_C. Balls and Boxes

Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.

Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i + 1, i + 2, i + 3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i = n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on.

For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i = 3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4, 1, 2, 3, 4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.

At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x — the number of the box, where he put the last of the taken out balls.

He asks you to help to find the initial arrangement of the balls in the boxes.

Input

The first line of the input contains two integers n and x (2 ≤ n ≤ 105, 1 ≤ x ≤ n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a1, a2, ..., an, where integer ai (0 ≤ ai ≤ 109, ax ≠ 0) represents the number of balls in the box with index i after Vasya completes all the actions.

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

Output

Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them.

Examples

Input

4 4
4 3 1 6

Output

3 2 5 4

Input

5 2
3 2 0 2 7

Output

2 1 4 1 6

Input

3 3
2 3 1

Output

1 2 3

```python
n, x = map(int,input().split())
a = [int(i) for i in input().split()]
j = x - 1
z = min(a)
while a[j] != z:
    if j == 0:
        j = n - 1
    else:
        j -= 1
m = a[j]
k = 0
if x - 1 > j:
    for i in range(n):
        if j < i <= x - 1:
            a[i] -= (m + 1)
            k += (m + 1)
        else:
            a[i] -= m
            k += m
    a[j] += k
elif x - 1 < j:
    for i in range(n):
        if x - 1 < i <= j:
            a[i] -= m
            k += m
        else:
            a[i] -=(m + 1)
            k += (m + 1)
    a[j] += k
else:
    for i in range(n):
        a[i] -= m
        k += m
    a[j] += k
print(*a)

```


284_C. Cows and Sequence

Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following:

  1. Add the integer xi to the first ai elements of the sequence.
  2. Append an integer ki to the end of the sequence. (And hence the size of the sequence increases by 1)
  3. Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence.

After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!

Input

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of operations. The next n lines describe the operations. Each line will start with an integer ti (1 ≤ ti ≤ 3), denoting the type of the operation (see above). If ti = 1, it will be followed by two integers ai, xi (|xi| ≤ 103; 1 ≤ ai). If ti = 2, it will be followed by a single integer ki (|ki| ≤ 103). If ti = 3, it will not be followed by anything.

It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence.

Output

Output n lines each containing the average of the numbers in the sequence after the corresponding operation.

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

Examples

Input

5
2 1
3
2 3
2 1
3

Output

0.500000
0.000000
1.500000
1.333333
1.500000

Input

6
2 1
1 2 20
2 2
1 2 -3
3
3

Output

0.500000
20.500000
14.333333
12.333333
17.500000
17.000000

Note

In the second sample, the sequence becomes <image>

```python
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

n=Int()

s=0
top=[0]

for i in range(n):
    query=input()

    if(query[0]=='1'):
        _,a,x=[int(i) for i in query.split()]
        s+=a*x
        top[a-1]+=x

    elif(query[0]=='2'):
        _,x=[int(i) for i in query.split()]
        s+=x
        top[-1]-=x
        top.append(x)
    else:
        ele=top.pop()
        s-=ele
        top[-1]+=ele

    print(s/len(top))

```


332_A. Down the Hatch!

Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!

Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that:

  1. he pointed at the person with index (bi + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y);
  2. if j ≥ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice;
  3. the turn went to person number (bi + 1) mod n.

The person who was pointed on the last turn did not make any actions.

The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.

You can assume that in any scenario, there is enough juice for everybody.

Input

The first line contains a single integer n (4 ≤ n ≤ 2000) — the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns.

Output

Print a single integer — the number of glasses of juice Vasya could have drunk if he had played optimally well.

Examples

Input

4
abbba

Output

1

Input

4
abbab

Output

0

Note

In both samples Vasya has got two turns — 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different.

```python
n = int(input())
moves = input()
i = n
count = 0
while(i < len(moves)):
    m = moves[i - 1]
    if(m == moves[i - 2] and m == moves[i - 3] and m == moves[i - 3]):
        count += 1
    i += n
print(count)
```


355_A. Vasya and Digital Root

Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.

Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to:

  1. dr(n) = S(n), if S(n) < 10;
  2. dr(n) = dr( S(n) ), if S(n) ≥ 10.

For example, dr(4098) = dr(21) = 3.

Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n) = S( S( S( S(n) ) ) ) (n ≤ 101000).

Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist.

Input

The first line contains two integers k and d (1 ≤ k ≤ 1000; 0 ≤ d ≤ 9).

Output

In a single line print either any number that meets the requirements (without the leading zeroes) or "No solution" (without the quotes), if the corresponding number does not exist.

The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes.

Examples

Input

4 4

Output

5881

Input

5 1

Output

36172

Input

1 0

Output

0

Note

For the first test sample dr(5881) = dr(22) = 4.

For the second test sample dr(36172) = dr(19) = dr(10) = 1.

```python
k,d=map(int,input().split())
if(k==1 and d==0):
    print(0)
elif(d==0):
    print("No solution")
else:
    print(str(d)+('0'*(k-1)))

```


379_B. New Year Present

The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception.

Vasily knows that the best present is (no, it's not a contest) money. He's put n empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided to put ai coins to the i-th wallet from the left.

Vasily is a very busy man, so the money are sorted into the bags by his robot. Initially, the robot stands by the leftmost wallet in the row. The robot can follow instructions of three types: go to the wallet that is to the left of the current one (if such wallet exists), go to the wallet that is to the right of the current one (if such wallet exists), put a coin to the current wallet. Due to some technical malfunctions the robot cannot follow two "put a coin" instructions in a row.

Vasily doesn't want to wait for long, so he wants to write a program for the robot that contains at most 106 operations (not necessarily minimum in length) the robot can use to put coins into the wallets. Help him.

Input

The first line contains integer n (2 ≤ n ≤ 300) — the number of wallets. The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 300).

It is guaranteed that at least one ai is positive.

Output

Print the sequence that consists of k (1 ≤ k ≤ 106) characters, each of them equals: "L", "R" or "P". Each character of the sequence is an instruction to the robot. Character "L" orders to move to the left, character "R" orders to move to the right, character "P" orders the robot to put a coin in the wallet. The robot is not allowed to go beyond the wallet line. In other words, you cannot give instructions "L" if the robot is at wallet 1, or "R" at wallet n.

As a result of the performed operations, the i-th wallet from the left must contain exactly ai coins. If there are multiple answers, you can print any of them.

Examples

Input

2
1 2

Output

PRPLRP

Input

4
0 2 0 2

Output

RPRRPLLPLRRRP

```python
n = int(input())
l = [int(x) for x in input().split()]
s = ''
for x in l[:-1]:
	if x:
		s += 'P'
		for i in range(x - 1):
			s += 'RLP'
	s += 'R'
if l[-1]:
	s += 'P'
	for i in range(l[-1] - 1):
		s += 'LRP'
print(s)

```


44_C. Holidays

School holidays come in Berland. The holidays are going to continue for n days. The students of school №N are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are in charge of the daily watering of flowers in shifts according to the schedule. However when Marina Sergeyevna was making the schedule, she was so tired from work and so lost in dreams of the oncoming vacation that she perhaps made several mistakes. In fact, it is possible that according to the schedule, on some days during the holidays the flowers will not be watered or will be watered multiple times. Help Marina Sergeyevna to find a mistake.

Input

The first input line contains two numbers n and m (1 ≤ n, m ≤ 100) — the number of days in Berland holidays and the number of people in charge of the watering respectively. The next m lines contain the description of the duty schedule. Each line contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), meaning that the i-th person in charge should water the flowers from the ai-th to the bi-th day inclusively, once a day. The duty shifts are described sequentially, i.e. bi ≤ ai + 1 for all i from 1 to n - 1 inclusively.

Output

Print "OK" (without quotes), if the schedule does not contain mistakes. Otherwise you have to find the minimal number of a day when the flowers will not be watered or will be watered multiple times, and output two integers — the day number and the number of times the flowers will be watered that day.

Examples

Input

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

Output

OK

Input

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

Output

2 2

Input

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

Output

4 0

Note

Keep in mind that in the second sample the mistake occurs not only on the second day, but also on the sixth day, when nobody waters the flowers. However, you have to print the second day, i.e. the day with the minimal number.

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

c = [0] * n

for i in range(m):

    a, b = map(int, input().split())

    for j in range(a - 1, b):

        c[j] += 1

for i in range(n):

    if c[i] != 1:

        print(i + 1, c[i])

        exit()

print('OK')

# Made By Mostafa_Khaled
```


519_C. A and B and Team Training

A and B are preparing themselves for programming contests.

An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solving problems together with experienced participants.

A believes that the optimal team of three people should consist of one experienced participant and two newbies. Thus, each experienced participant can share the experience with a large number of people.

However, B believes that the optimal team should have two experienced members plus one newbie. Thus, each newbie can gain more knowledge and experience.

As a result, A and B have decided that all the teams during the training session should belong to one of the two types described above. Furthermore, they agree that the total number of teams should be as much as possible.

There are n experienced members and m newbies on the training session. Can you calculate what maximum number of teams can be formed?

Input

The first line contains two integers n and m (0 ≤ n, m ≤ 5·105) — the number of experienced participants and newbies that are present at the training session.

Output

Print the maximum number of teams that can be formed.

Examples

Input

2 6

Output

2

Input

4 5

Output

3

Note

Let's represent the experienced players as XP and newbies as NB.

In the first test the teams look as follows: (XP, NB, NB), (XP, NB, NB).

In the second test sample the teams look as follows: (XP, NB, NB), (XP, NB, NB), (XP, XP, NB).

```python
a, b = map(int, input().split())
a, b = min(a, b), max(a, b)
if b-a >= a: print(a)
else:
    res = b-a
    a -= res
    res += (a//3)*2
    if a%3 == 2: res += 1
    print(res)

```


545_D. Queue

Little girl Susie went shopping with her mom and she wondered how to improve service quality.

There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed.

Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.

Input

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

The next line contains n integers ti (1 ≤ ti ≤ 109), separated by spaces.

Output

Print a single number — the maximum number of not disappointed people in the queue.

Examples

Input

5
15 2 1 5 3

Output

4

Note

Value 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.

```python
n=int(input())
l=list(map(int,input().split()))
l.sort()
s=0
c=0
for i in l:
    if(i>=s):
        c=c+1
        s=s+i
print(c)

```


572_A. Arrays

You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.

Input

The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly.

The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space.

The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A.

The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.

Output

Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).

Examples

Input

3 3
2 1
1 2 3
3 4 5

Output

YES

Input

3 3
3 3
1 2 3
3 4 5

Output

NO

Input

5 2
3 1
1 1 1 1 1
2 2

Output

YES

Note

In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).

In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: <image>.

```python
na,nb=map(int,input().split())
k,m=map(int,input().split())
a=[int(z)for z in input().split()]
b=[int(z)for z in input().split()]
print("YNEOS"[a[k-1]>=b[-m]::2])
# Interesting. --YKF

```


615_B. Longtail Hedgehog

This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions:

  1. Only segments already presented on the picture can be painted;
  2. The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment;
  3. The numbers of points from the beginning of the tail to the end should strictly increase.

Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.

Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.

Input

First line of the input contains two integers n and m(2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number segments on the picture respectively.

Then follow m lines, each containing two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.

Output

Print the maximum possible value of the hedgehog's beauty.

Examples

Input

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

Output

9

Input

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

Output

12

Note

The picture below corresponds to the first sample. Segments that form the hedgehog are painted red. The tail consists of a sequence of points with numbers 1, 2 and 5. The following segments are spines: (2, 5), (3, 5) and (4, 5). Therefore, the beauty of the hedgehog is equal to 3·3 = 9.

<image>

```python
from sys import stdin,stdout,setrecursionlimit
setrecursionlimit(10**5)
from collections import defaultdict
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
PI=float('inf')
def dfs(src):
    vis[src]=1
    for neigh in g[src]:
        if neigh<src:
            if not vis[neigh]:dfs(neigh)
            dp[src]=max(dp[src],1+dp[neigh])
for _ in range(1):#nmbr()):
    n,eg=lst()
    g=defaultdict(list)
    for i in range(eg):
        u,v=lst()
        g[u]+=[v]
        g[v]+=[u]
    dp=[1]*(1+n)
    vis=[0]*(1+n)
    for node in range(1,n+1):
        if not vis[node]:dfs(node)
    print(max(len(g[node])*dp[node] for node in range(1,n+1)))
```


634_D. Package Delivery

Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.

Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point xi on the number line and sells an unlimited amount of fuel at a price of pi dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.

Input

The first line of input contains three space separated integers d, n, and m (1 ≤ n ≤ d ≤ 109, 1 ≤ m ≤ 200 000) — the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively.

Each of the next m lines contains two integers xi, pi (1 ≤ xi ≤ d - 1, 1 ≤ pi ≤ 106) — the position and cost of gas at the i-th gas station. It is guaranteed that the positions of the gas stations are distinct.

Output

Print a single integer — the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.

Examples

Input

10 4 4
3 5
5 8
6 3
8 4

Output

22

Input

16 5 2
8 2
5 1

Output

-1

Note

In the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2·5 + 4·3 = 22 dollars.

In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.

```python
destination, max_gas_tank_volume, gas_prices_number = map(int, input().split())
start_point = 0
gas_prices = {start_point:0}
for i in range(gas_prices_number):
    coordinate, price = map(int, input().split())
    gas_prices[coordinate] = price
points = sorted(gas_prices.keys(), reverse = True)
current_point = start_point
count = 0
gas_tank_volume = max_gas_tank_volume
reachable_points = []
while current_point != destination:
    farthest_reachable_point = current_point + max_gas_tank_volume
    while points and points[-1] <= farthest_reachable_point:
        reachable_points.append(points.pop())
    if reachable_points:
        cheaper_reachable_points = sorted(filter(lambda point: gas_prices[point] < gas_prices[current_point], reachable_points))
        next_point = cheaper_reachable_points[0] if cheaper_reachable_points else min(reachable_points, key = lambda point: gas_prices[point])
        if farthest_reachable_point >= destination and (current_point == start_point or gas_prices[next_point] >= gas_prices[current_point]):
            next_point = destination
        else:
            reachable_points = [point for point in reachable_points if point > next_point]
    else:
        if farthest_reachable_point >= destination:
            next_point = destination
        else:
            count = -1
            break
    distantion = next_point - current_point
    if next_point != destination and gas_prices[current_point] <= gas_prices[next_point]:
        required_gas_volume = max_gas_tank_volume
    else:
        required_gas_volume = distantion
    if required_gas_volume > gas_tank_volume:
        count += (required_gas_volume - gas_tank_volume)*gas_prices[current_point]
        gas_tank_volume = required_gas_volume
    current_point = next_point
    gas_tank_volume -= distantion
print(count)

```


663_B. International Olympiad

International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.

For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.

You are given a list of abbreviations. For each of them determine the year it stands for.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process.

Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.

Output

For each abbreviation given in the input, find the year of the corresponding Olympiad.

Examples

Input

5
IAO'15
IAO'2015
IAO'1
IAO'9
IAO'0

Output

2015
12015
1991
1989
1990

Input

4
IAO'9
IAO'99
IAO'999
IAO'9999

Output

1989
1999
2999
9999


755_A. PolandBall and Hypothesis

PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number".

Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Could you prove it wrong? Write a program that finds a counterexample for any n.

Input

The only number in the input is n (1 ≤ n ≤ 1000) — number from the PolandBall's hypothesis.

Output

Output such m that n·m + 1 is not a prime number. Your answer will be considered correct if you output any suitable m such that 1 ≤ m ≤ 103. It is guaranteed the the answer exists.

Examples

Input

3

Output

1

Input

4

Output

2

Note

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

For the first sample testcase, 3·1 + 1 = 4. We can output 1.

In the second sample testcase, 4·1 + 1 = 5. We cannot output 1 because 5 is prime. However, m = 2 is okay since 4·2 + 1 = 9, which is not a prime number.

```python
import sys

n = int(input())

for m in range(1, 1001):
        for j in range(2, 1001):
            if j < (n * m + 1) and (n * m + 1) % j == 0:
                print(m)
                sys.exit(0)
```


776_B. Sherlock and his girlfriend

Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.

He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.

Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.

Help Sherlock complete this trivial task.

Input

The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces.

Output

The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints.

The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price.

If there are multiple ways to color the pieces using k colors, you can output any of them.

Examples

Input

3

Output

2
1 1 2

Input

4

Output

2
2 1 1 2

Note

In the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.

In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.

```python
def sieve(n):
	mark = [True]*(n+1)
	p = 2
	while p*p<=n:
		if mark[p]:
			for i in range(p*p,n+1,p):
				mark[i] = False
		p+=1
	for i in range(2,n+1):
		if mark[i]:
			print(1,end=" ")
		else:
			print(2,end=" ")
n = int(input())
if n==1 or n==2:
	print(1)
else:
	print(2)
sieve(n+1)
```


7_C. Line

A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from  - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist.

Input

The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corresponding coefficients of the line equation. It is guaranteed that A2 + B2 > 0.

Output

If the required point exists, output its coordinates, otherwise output -1.

Examples

Input

2 5 3

Output

6 -3

```python
def gcd(x,y):
    if x % y == 0:
        return y
    else:
        return gcd(y,x%y)

def bezout(x,y):
    if x % y == 0:
        return (0,1)
    else:
        t,s = bezout (y,x%y)
        return (s,t-(x//y)*s)

a,b,c = map(int,input().split())
if a == 0:
    if c % b == 0:
        print("%d %d" % (0,-c//b))
    else:
        print(-1)
    exit()
if b == 0:
    if c % a == 0:
        print("%d %d" % (-c//a,0))
    else:
        print(-1)
    exit()
if c % gcd(a,b) != 0:
    print(-1)
else:
    x,y = bezout(a,b)
    m = -c//gcd(a,b)
    print("%d %d" % (m*x,m*y))
```


846_F. Random Query

You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the array from index l to index r, inclusive (1-indexed).

Input

The first line contains one integer number n (1 ≤ n ≤ 106). The second line contains n integer numbers a1, a2, ... an (1 ≤ ai ≤ 106) — elements of the array.

Output

Print one number — the expected number of unique elements in chosen segment.

Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 4 — formally, the answer is correct if <image>, where x is jury's answer, and y is your answer.

Examples

Input

2
1 2

Output

1.500000

Input

2
2 2

Output

1.000000

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

lastocc=[0]*1000006
ans=[0]*n
ans[0]=1
lastocc[a[0]]=1

for i in range(1,n):
    ans[i]=ans[i-1]+(i+1-lastocc[a[i]])
    lastocc[a[i]]=i+1

print((2*sum(ans)-n)/(n*n))

```


868_B. Race Against Time

Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other.

The entire universe turned into an enormous clock face with three hands — hour, minute, and second. Time froze, and clocks now show the time h hours, m minutes, s seconds.

Last time Misha talked with the coordinator at t1 o'clock, so now he stands on the number t1 on the clock face. The contest should be ready by t2 o'clock. In the terms of paradox it means that Misha has to go to number t2 somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction.

Clock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way).

Given the hands' positions, t1, and t2, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from t1 to t2 by the clock face.

Input

Five integers h, m, s, t1, t2 (1 ≤ h ≤ 12, 0 ≤ m, s ≤ 59, 1 ≤ t1, t2 ≤ 12, t1 ≠ t2).

Misha's position and the target time do not coincide with the position of any hand.

Output

Print "YES" (quotes for clarity), if Misha can prepare the contest on time, and "NO" otherwise.

You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").

Examples

Input

12 30 45 3 11

Output

NO

Input

12 0 1 12 1

Output

YES

Input

3 47 0 4 9

Output

YES

Note

The three examples are shown on the pictures below from left to right. The starting position of Misha is shown with green, the ending position is shown with pink. Note that the positions of the hands on the pictures are not exact, but are close to the exact and the answer is the same.

<image>