1473_E. Minimum Path

You are given a weighted undirected connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.

Let's define the weight of the path consisting of k edges with indices e_1, e_2, ..., e_k as ∑_{i=1}^{k}{w_{e_i}} - max_{i=1}^{k}{w_{e_i}} + min_{i=1}^{k}{w_{e_i}}, where w_i — weight of the i-th edge in the graph.

Your task is to find the minimum weight of the path from the 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).

Input

The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and the number of edges in the graph.

Following m lines contains three integers v_i, u_i, w_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^9; v_i ≠ u_i) — endpoints of the i-th edge and its weight respectively.

Output

Print n-1 integers — the minimum weight of the path from 1-st vertex to the i-th vertex for each i (2 ≤ i ≤ n).

Examples

Input

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

Output

1 2 2 4

Input

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

Output

2 1 4 3 1

Input

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

Output

3 4 2 7 7 3

```python
import io
import os

# import __pypy__

def dijkstra(*args):
    # return dijkstraHeap(*args)  # 2979 ms
    return dijkstraHeapComparatorWrong(*args)  # 2823 ms
    # return dijkstraHeapComparator(*args)  # 2370 ms
    # return dijkstraSegTree(*args)  # 2417 ms with inf=float('inf), 2995 ms with inf=-1
    # return dijkstraSortedList(*args) # 2995 ms

def dijkstraHeap(source, N, getAdj):
    # Heap of (dist, node)

    # Use float for dist because max dist for this problem doesn't fit in 32-bit
    # Then node has to be a float too, because `(float, int)` will use `W_SpecialisedTupleObject_oo` but we want `W_SpecialisedTupleObject_ff`

    from heapq import heappop, heappush

    inf = float("inf")
    dist = [inf] * N
    dist[source] = 0.0
    queue = [(0.0, float(source))]
    # print(__pypy__.internal_repr(queue[0])) # W_SpecialisedTupleObject_ff
    # print(__pypy__.strategy(dist)) # FloatListStrategy
    while queue:
        d, u = heappop(queue)
        u = int(u)
        if dist[u] == d:
            for v, w in getAdj(u):
                cost = d + w
                if cost < dist[v]:
                    dist[v] = cost
                    heappush(queue, (cost, float(v)))
    return dist

def dijkstraHeapComparatorWrong(source, N, getAdj):
    # Heap of nodes, sorted with a comparator
    # This implementation is actually incorrect but kept for reference since it performs well when using a SPFA-like heuristic
    # Note: normal SPFA will TLE since there's a uphack for it in testcase #62

    inf = float("inf")
    dist = [inf] * N
    dist[source] = 0.0
    inQueue = [0] * N
    inQueue[source] = 1
    queue = [source]
    # print(__pypy__.strategy(queue)) # IntegerListStrategy

    def cmp_lt(u, v):
        return dist[u] < dist[v]

    heappush, heappop, _ = import_heapq(cmp_lt)

    while queue:
        u = heappop(queue)
        d = dist[u]
        inQueue[u] = 0
        for v, w in getAdj(u):
            cost = d + w
            if cost < dist[v]:
                dist[v] = cost
                if not inQueue[v]:
                    heappush(queue, v)
                    inQueue[v] = 1
                # If v is already in the queue, we were suppose to bubble it to fix heap invariant
    return dist

def dijkstraHeapComparator(source, N, getAdj):
    # Same above, except correctly re-bubbling the key after updates

    inf = float("inf")
    dist = [inf] * N
    dist[source] = 0.0

    def cmp_lt(u, v):
        return dist[u] < dist[v]

    heappush, heappop, _siftdown = import_heapq(cmp_lt)

    class ListWrapper:
        # Exactly like a regular list except with fast .index(x) meant to be used with heapq
        # Not general purpose and relies on the exact heapq implementation for correctness (swaps only, added via append, deleted via pop)

        def __init__(self, maxN):
            self.arr = []
            self.loc = [-1] * maxN

        def append(self, x):
            arr = self.arr
            arr.append(x)
            self.loc[x] = len(arr) - 1

        def pop(self):
            ret = self.arr.pop()
            self.loc[ret] = -1
            return ret

        def index(self, x):
            return self.loc[x]

        def __setitem__(self, i, x):
            self.arr[i] = x
            self.loc[x] = i

        def __getitem__(self, i):
            return self.arr[i]

        def __len__(self):
            return len(self.arr)

    queue = ListWrapper(N)
    queue.append(source)
    # print(__pypy__.strategy(queue.arr)) # IntegerListStrategy

    while queue:
        u = heappop(queue)
        d = dist[u]
        for v, w in getAdj(u):
            cost = d + w
            if cost < dist[v]:
                dist[v] = cost
                heapIndex = queue.index(v)
                if heapIndex == -1:
                    heappush(queue, v)
                else:
                    _siftdown(queue, 0, heapIndex)
    return dist

def dijkstraSegTree(start, n, getAdj):
    # From pajenegod: https://github.com/cheran-senthil/PyRival/pull/55
    # Modifications:
    #   Use floats instead of ints for inf/_min
    #   Fix typo: m -> self.m
    #   Fix python 3 compatibility: __getitem__
    #   Cache self.data
    #   Remove parent pointers

    if False:
        inf = -1

        def _min(a, b):
            return a if b == inf or inf != a < b else b

    else:
        inf = float("inf")
        _min = min

    class DistanceKeeper:
        def __init__(self, n):
            m = 1
            while m < n:
                m *= 2
            self.m = m
            self.data = 2 * m * [inf]
            self.dist = n * [inf]

        def __getitem__(self, x):
            return self.dist[x]

        def __setitem__(self, ind, x):
            data = self.data
            self.dist[ind] = x
            ind += self.m
            data[ind] = x
            ind >>= 1
            while ind:
                data[ind] = _min(data[2 * ind], data[2 * ind + 1])
                ind >>= 1

        def trav(self):
            m = self.m
            data = self.data
            dist = self.dist
            while data[1] != inf:
                x = data[1]

                ind = 1
                while ind < m:
                    ind = 2 * ind + (data[2 * ind] != x)
                ind -= m

                self[ind] = inf
                dist[ind] = x
                yield ind

    # P = [-1] * n
    D = DistanceKeeper(n)
    D[start] = 0.0

    for node in D.trav():
        for nei, weight in getAdj(node):
            new_dist = D[node] + weight
            if D[nei] == inf or new_dist < D[nei]:
                D[nei] = new_dist
                # P[nei] = node
    # print(__pypy__.strategy(D.dist))
    # print(__pypy__.strategy(D.data))
    return D.dist

def dijkstraSortedList(source, N, getAdj):
    # Just for completeness

    # COPY AND PASTE from https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
    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))

    # END COPY AND PASTE #####################################

    inf = float("inf")
    dist = [inf] * N
    dist[source] = 0.0
    queue = SortedList([(0.0, float(source))])
    while queue:
        negD, u = queue.pop(-1)
        d = -negD
        u = int(u)
        for v, w in getAdj(u):
            prevCost = dist[v]
            cost = d + w
            if cost < prevCost:
                if prevCost != inf:
                    queue.discard((-prevCost, float(v)))
                dist[v] = cost
                queue.add((-cost, float(v)))
    return dist

def import_heapq(cmp_lt):
    # Python 2 has a heapq.cmp_lt but python 3 removed it
    # Add it back for pypy3 submissions

    import sys

    if sys.version_info < (3,):
        # Python 2
        import heapq
        from heapq import heappush, heappop, _siftdown

        heapq.cmp_lt = cmp_lt
    else:
        # Python 3
        # COPY AND PASTE python 2.7 heapq from https://github.com/python/cpython/blob/2.7/Lib/heapq.py

        def heappush(heap, item):
            """Push item onto heap, maintaining the heap invariant."""
            heap.append(item)
            _siftdown(heap, 0, len(heap) - 1)

        def heappop(heap):
            """Pop the smallest item off the heap, maintaining the heap invariant."""
            lastelt = heap.pop()  # raises appropriate IndexError if heap is empty
            if heap:
                returnitem = heap[0]
                heap[0] = lastelt
                _siftup(heap, 0)
                return returnitem
            return lastelt

        def _siftdown(heap, startpos, pos):
            newitem = heap[pos]
            # Follow the path to the root, moving parents down until finding a place
            # newitem fits.
            while pos > startpos:
                parentpos = (pos - 1) >> 1
                parent = heap[parentpos]
                if cmp_lt(newitem, parent):
                    heap[pos] = parent
                    pos = parentpos
                    continue
                break
            heap[pos] = newitem

        def _siftup(heap, pos):
            endpos = len(heap)
            startpos = pos
            newitem = heap[pos]
            # Bubble up the smaller child until hitting a leaf.
            childpos = 2 * pos + 1  # leftmost child position
            while childpos < endpos:
                # Set childpos to index of smaller child.
                rightpos = childpos + 1
                if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
                    childpos = rightpos
                # Move the smaller child up.
                heap[pos] = heap[childpos]
                pos = childpos
                childpos = 2 * pos + 1
            # The leaf at pos is empty now.  Put newitem there, and bubble it up
            # to its final resting place (by sifting its parents down).
            heap[pos] = newitem
            _siftdown(heap, startpos, pos)

        # END COPY AND PASTE ###############################
    return heappush, heappop, _siftdown

if __name__ == "__main__":
    input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

    N, M = [int(x) for x in input().split()]
    graph = [[] for i in range(N)]
    for i in range(M):
        u, v, w = [int(x) for x in input().split()]
        u -= 1
        v -= 1
        graph[u].append((v, w))
        graph[v].append((u, w))

    # Want shortest path except one edge is worth 0 and one edge is worth 2x
    # Track this with 2 bits of extra state
    def getAdj(node):
        u = node >> 2
        state = node & 3
        for v, w in graph[u]:
            vBase = v << 2
            # Regular edge
            yield vBase | state, w
            if not state & 1:
                # Take max edge, worth 0
                yield vBase | state | 1, 0
            if not state & 2:
                # Take min edge, worth double
                yield vBase | state | 2, 2 * w
            if not state & 3:
                # Take both min and max edge, worth normal
                yield vBase | state | 3, w

    dist = dijkstra(0, 4 * N, getAdj)
    print(" ".join(str(int(dist[(u << 2) | 3])) for u in range(1, N)))

```


1521_E. Nastia and a Beautiful Matrix

You like numbers, don't you? Nastia has a lot of numbers and she wants to share them with you! Isn't it amazing?

Let a_i be how many numbers i (1 ≤ i ≤ k) you have.

An n × n matrix is called beautiful if it contains all the numbers you have, and for each 2 × 2 submatrix of the original matrix is satisfied:

  1. The number of occupied cells doesn't exceed 3;
  2. The numbers on each diagonal are distinct.

Make a beautiful matrix of minimum size.

Input

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

The first line of each test case contains 2 integers m and k (1 ≤ m, k ≤ 10^5) — how many numbers Nastia gave you and the length of the array a, respectively.

The second line of each test case contains k integers a_1, a_2, …, a_{k} (0 ≤ a_i ≤ m, a_1 + a_2 + … + a_{k} = m), where a_i is how many numbers i you have.

It's guaranteed that the sum of m and k in one test doesn't exceed 2 ⋅ 10^5.

Output

For each t test case print a single integer n — the size of the beautiful matrix.

In the next n lines print n integers b_{i, j} (0 ≤ b_{i, j} ≤ k; if position is empty, print b_{i, j} = 0) — the beautiful matrix b you made up.

Example

Input

2
3 4
2 0 0 1
15 4
2 4 8 1

Output

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

Note

Note that 0 in this problem represents a blank, not a number.

Examples of possible answers for the first test case:

\begin{array}{cc} 1 & 1 \\\ 4 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 4 \\\ 1 & 0 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 0 \\\ 1 & 1 \\\ \end{array}

Examples of not beautiful matrices for the first test case:

\begin{array}{cc} 1 & 0 \\\ 4 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 4 & 1 \\\ 7 & 1 \\\ \end{array} \hspace{0,5cm} \begin{array}{cc} 1 & 0 \\\ 4 & 0 \\\ \end{array}

The example of the not beautiful matrix for the second test case:

\begin{array}{cc} 3 & 4 & 0 & 2 & 2 \\\ 3 & 2 & 3 & 3 & 0 \\\ 0 & 1 & 0 & 0 & 0 \\\ 3 & 0 & 0 & 0 & 0 \\\ 2 & 1 & 3 & 3 & 3 \\\ \end{array}

Everything is okay, except the left-top submatrix contains 4 numbers.

```python
def cheak(x):
    return x**2-(x//2)**2>=m and x*(x//2+(1 if x%2!=0 else 0))>=mx
for test in range(int(input())):
    m,k=(int(i) for i in input().split())
    a=[int(i) for i in input().split()]
    mx=max(a)
    z=0;y=m*4
    while z!=y:
        x=(z+y)//2
        if cheak(x):
            y=x
        else:
            z=x+1
    else:
        x=z
    a=sorted(list(map(list,zip(a,range(1,len(a)+1)))))
    def get():
        i=len(a)
        while i!=0:
            i-=1
            while a[i][0]>0:
                a[i][0]-=1
                yield a[i][1]
        yield 0
    mt=[[0 for i in range(x)] for j in range(x)]
    t=1
    it=get()
    for i in range(0,x,2):
        if t==0:break
        for j in range(1,x,2):
            t=next(it)
            if t:mt[i][j]=t
            else:break
    for i in range(0,x,2):
        if t==0:break
        for j in range(0,x,2):
            t=next(it)
            if t:mt[i][j]=t
            else:break
    for i in range(1,x,2):
        if t==0:break
        for j in range(0,x,2):
            t=next(it)
            if t:mt[i][j]=t
            else:break
    print(len(mt))
    for i in mt:
        print(*i)
```


1550_E. Stringforces

You are given a string s of length n. Each character is either one of the first k lowercase Latin letters or a question mark.

You are asked to replace every question mark with one of the first k lowercase Latin letters in such a way that the following value is maximized.

Let f_i be the maximum length substring of string s, which consists entirely of the i-th Latin letter. A substring of a string is a contiguous subsequence of that string. If the i-th letter doesn't appear in a string, then f_i is equal to 0.

The value of a string s is the minimum value among f_i for all i from 1 to k.

What is the maximum value the string can have?

Input

The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 17) — the length of the string and the number of first Latin letters used.

The second line contains a string s, consisting of n characters. Each character is either one of the first k lowercase Latin letters or a question mark.

Output

Print a single integer — the maximum value of the string after every question mark is replaced with one of the first k lowercase Latin letters.

Examples

Input

10 2
a??ab????b

Output

4

Input

9 4
?????????

Output

2

Input

2 3
??

Output

0

Input

15 3
??b?babbc??b?aa

Output

3

Input

4 4
cabd

Output

1

Note

In the first example the question marks can be replaced in the following way: "aaaababbbb". f_1 = 4, f_2 = 4, thus the answer is 4. Replacing it like this is also possible: "aaaabbbbbb". That way f_1 = 4, f_2 = 6, however, the minimum of them is still 4.

In the second example one of the possible strings is "aabbccdda".

In the third example at least one letter won't appear in the string, thus, the minimum of values f_i is always 0.

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

n, k = map(int, input().split())
s = input()[:-1]
left, right = 0, n
while left < right:
    mid = right - (right - left) // 2
    A = [[0] * (n + 2) for _ in range(k)]

    for c in range(k):
        A[c][n] = A[c][n + 1] = n + 1
        L = 0
        for i in range(n - 1, -1, -1):
            if s[i] == '?' or ord(s[i]) - ord('a') == c: L += 1
            else: L = 0
            A[c][i] = i + mid if L >= mid else A[c][i + 1]

    dp = [n + 1] * (1 << k)
    dp[0] = 0
    for mask in range(1 << k):
        for i in range(k):
            if mask >> k & 1: continue
            t = mask | 1 << i
            dp[t] = min(dp[t], A[i][dp[mask]])
    if dp[-1] <= n: left = mid
    else: right = mid - 1
print(left)
```


177_B1. Rectangular Game

The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.

<image> 10 pebbles are arranged in two rows, each row has 5 pebbles

Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.

The game process can be represented as a finite sequence of integers c1, ..., ck, where:

  * c1 = n
  * ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
  * ck = 1

The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.

Input

The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.

The input limitations for getting 30 points are:

  * 2 ≤ n ≤ 50

The input limitations for getting 100 points are:

  * 2 ≤ n ≤ 109

Output

Print a single number — the maximum possible result of the game.

Examples

Input

10

Output

16

Input

8

Output

15

Note

Consider the first example (c1 = 10). The possible options for the game development are:

  * Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
  * Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
  * Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.


221_A. Little Elephant and Function

The Little Elephant enjoys recursive functions.

This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:

  * If x = 1, exit the function.
  * Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a).

The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.

Input

A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation.

Output

In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces.

It is guaranteed that the answer exists.

Examples

Input

1

Output

1

Input

2

Output

2 1

```python
n=int(input())
l=list(range(1,n+1))
l=sorted(l)
l.insert(0,l[-1])
l.pop()
print(*l)
```


245_B. Internet Address

Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format:

<protocol>://<domain>.ru[/<context>]

where:

  * <protocol> can equal either "http" (without the quotes) or "ftp" (without the quotes),
  * <domain> is a non-empty string, consisting of lowercase English letters,
  * the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters.

If string <context> isn't present in the address, then the additional character "/" isn't written. Thus, the address has either two characters "/" (the ones that go before the domain), or three (an extra one in front of the context).

When the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters ":", "/", ".".

Help Vasya to restore the possible address of the recorded Internet resource.

Input

The first line contains a non-empty string that Vasya wrote out in his notebook. This line consists of lowercase English letters only.

It is guaranteed that the given string contains at most 50 letters. It is guaranteed that the given string can be obtained from some correct Internet resource address, described above.

Output

Print a single line — the address of the Internet resource that Vasya liked. If there are several addresses that meet the problem limitations, you are allowed to print any of them.

Examples

Input

httpsunrux

Output

http://sun.ru/x

Input

ftphttprururu

Output

ftp://http.ru/ruru

Note

In the second sample there are two more possible answers: "ftp://httpruru.ru" and "ftp://httpru.ru/ru".

```python
s = input()
if s[:3] == "ftp":
    pre = "ftp://"
    s = s[3:]
elif s[:4] == "http":
    pre = "http://"
    s = s[4:]
index = s[1:].index("ru")+1
if index == len(s)-2:
    s = pre+s[:index]+"."+s[index:]
else:
    s = pre+s[:index]+"."+s[index:index+2]+"/"+s[index+2:]
print(s)

```


26_E. Multithreading

You are given the following concurrent program. There are N processes and the i-th process has the following pseudocode:

    repeat ni times
        yi := y
        y := yi + 1
    end repeat

Here y is a shared variable. Everything else is local for the process. All actions on a given row are atomic, i.e. when the process starts executing a row it is never interrupted. Beyond that all interleavings are possible, i.e. every process that has yet work to do can be granted the rights to execute its next row. In the beginning y = 0. You will be given an integer W and ni, for i = 1, ... , N. Determine if it is possible that after all processes terminate, y = W, and if it is possible output an arbitrary schedule that will produce this final value.

Input

In the first line of the input you will be given two space separated integers N (1 ≤ N ≤ 100) and W ( - 109 ≤ W ≤ 109). In the second line there are N space separated integers ni (1 ≤ ni ≤ 1000).

Output

On the first line of the output write Yes if it is possible that at the end y = W, or No otherwise. If the answer is No then there is no second line, but if the answer is Yes, then on the second line output a space separated list of integers representing some schedule that leads to the desired result. For more information see note.

Examples

Input

1 10
11

Output

No

Input

2 3
4 4

Output

Yes
1 1 2 1 2 2 2 2 2 1 2 1 1 1 1 2

Input

3 6
1 2 3

Output

Yes
1 1 2 2 2 2 3 3 3 3 3 3

Note

For simplicity, assume that there is no repeat statement in the code of the processes, but the code from the loop is written the correct amount of times. The processes are numbered starting from 1. The list of integers represent which process works on its next instruction at a given step. For example, consider the schedule 1 2 2 1 3. First process 1 executes its first instruction, then process 2 executes its first two instructions, after that process 1 executes its second instruction, and finally process 3 executes its first instruction. The list must consists of exactly 2·Σ i = 1...N ni numbers.

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

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

n, w = map(int, input().split())
a = [0] + list(map(int, input().split()))
total = sum(a)

def ng():
    print('No')
    exit()

def ok(a):
    print('Yes')
    print(*a)
    exit()

if w < 1 or total < w:
    ng()

if n == 1:
    if w == a[1]:
        ok([1] * (a[1] * 2))
    else:
        ng()

if w == 1:
    if min(a[1:]) > 1:
        ng()

    min_i = a.index(1)
    ans = []
    for i in range(1, n + 1):
        if i == min_i:
            continue
        ans += [i] * (a[i] * 2)

    ok([min_i] + ans + [min_i])

ans1, ans2, ans3 = [], [], []
w -= 2
if w:
    for i in range(1, 3):
        x = min(a[i] - 1, w)
        w -= x
        a[i] -= x
        ans3 += [i] * (2 * x)
    for i in range(3, n + 1):
        x = min(a[i], w)
        w -= x
        a[i] -= x
        ans3 += [i] * (2 * x)

ans1 = [2] * ((a[2] - 1) * 2)
for i in range(3, n + 1):
    ans1 += [i] * (a[i] * 2)
ans1 = [1] + ans1 + [1]
a[1] -= 1

ans2 = [2] + [1] * (a[1] * 2) + [2]

if w == 0:
    ok(ans1 + ans2 + ans3)
else:
    ng()

```


340_E. Iahub and Permutations

Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.

The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge.

When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7).

Input

The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1.

It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.

Output

Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7).

Examples

Input

5
-1 -1 4 3 -1

Output

2

Note

For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.

```python
#lahub and Permutations
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
mod = 10**9+7
def pow(n,p,mod=mod): #繰り返し二乗法(nのp乗)
    res = 1
    while p > 0:
        if p % 2 == 0:
            n = n ** 2 % mod
            p //= 2
        else:
            res = res * n % mod
            p -= 1
    return res % mod

def factrial_memo(n=10**5,mod=mod):
    fact = [1, 1]
    for i in range(2, n + 1):
        fact.append((fact[-1] * i) % mod)
    return fact

fact = factrial_memo()

def permutation(n,r): #nPr
    return fact[n]*pow(fact[n-r],mod-2)%mod
def combination(n,r): #nCr
    return permutation(n,r)*pow(fact[r],mod-2)%mod
    #return fact[n]*pow(fact[n-r],mod-2)*pow(fact[r],mod-2)
def homogeneous(n,r): #nHr
    return combination(n+r-1,r)%mod
    #return fact[n+m-1]*pow(fact[n-1],mod-2)*pow(fact[r],mod-2)

n = int(readline())
lst1 = list(map(int,readline().split()))
ct = 0
lst2 = [0]*2_001
lst3 = [0]*2_001
for i in range(n):
    if i+1 == lst1[i]:
        print(0)
        exit()
    if lst1[i] == -1:
        ct += 1
        lst3[i+1] = 1
    else:
        lst2[lst1[i]] = 1

ct2 = 0
for i in range(1,n+1):
    if lst3[i] == 1 and lst2[i] == 0:
        ct2 += 1
#lst2:その場所が埋まってないindex
#lst3:その数字が使われてるindex
#何個入れちゃいけない位置に入れるかで数え上げる
#入れちゃいけないものはct2個って、
#ct-ct2個のものはどこに入れても要件を満たす

ans = 0
for i in range(ct2+1):
    ans += pow(-1,i)*combination(ct2,i)*fact[ct-i]
    ans %= mod
print(ans)
```


388_A. Fox and Box Accumulation

Fox Ciel has n boxes in her room. They have the same size and weight, but they might have different strength. The i-th box can hold at most xi boxes on its top (we'll call xi the strength of the box).

Since all the boxes have the same size, Ciel cannot put more than one box directly on the top of some box. For example, imagine Ciel has three boxes: the first has strength 2, the second has strength 1 and the third has strength 1. She cannot put the second and the third box simultaneously directly on the top of the first one. But she can put the second box directly on the top of the first one, and then the third box directly on the top of the second one. We will call such a construction of boxes a pile.

<image>

Fox Ciel wants to construct piles from all the boxes. Each pile will contain some boxes from top to bottom, and there cannot be more than xi boxes on the top of i-th box. What is the minimal number of piles she needs to construct?

Input

The first line contains an integer n (1 ≤ n ≤ 100). The next line contains n integers x1, x2, ..., xn (0 ≤ xi ≤ 100).

Output

Output a single integer — the minimal possible number of piles.

Examples

Input

3
0 0 10

Output

2

Input

5
0 1 2 3 4

Output

1

Input

4
0 0 0 0

Output

4

Input

9
0 1 0 2 0 1 1 2 10

Output

3

Note

In example 1, one optimal way is to build 2 piles: the first pile contains boxes 1 and 3 (from top to bottom), the second pile contains only box 2.

<image>

In example 2, we can build only 1 pile that contains boxes 1, 2, 3, 4, 5 (from top to bottom).

<image>

```python
I=lambda:list(map(int,input().split()))
n,=I()
l=I()
l.sort()
ans=0
i=0
k=1
while i<n:

    if l[i]<i//k:
        k+=1

    i+=1
print(k)

```


408_D. Long Path

One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.

The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 ≤ pi ≤ i.

In order not to get lost, Vasya decided to act as follows.

  * Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.
  * Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal.

Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.

Input

The first line contains integer n (1 ≤ n ≤ 103) — the number of rooms. The second line contains n integers pi (1 ≤ pi ≤ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.

Output

Print a single number — the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7).

Examples

Input

2
1 2

Output

4

Input

4
1 1 2 3

Output

20

Input

5
1 1 1 1 1

Output

62

```python
n = int(input())
a = list(map(int,input().split()))
values = [0 for k in range(n)]
for k in range(n) :
    back = a[k]
    if a[k] == k+1 :
        values[k] = 2
    else :
        values[k] += 2
        for t in range(a[k]-1,k) :
            values [k] += values[t]
        values[k] %= int(1e9 +7)
print(int(sum(values)%(1e9 + 7)))
```


459_A. Pashmak and Garden

Pashmak has fallen in love with an attractive girl called Parmida since one year ago...

Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.

Input

The first line contains four space-separated x1, y1, x2, y2 ( - 100 ≤ x1, y1, x2, y2 ≤ 100) integers, where x1 and y1 are coordinates of the first tree and x2 and y2 are coordinates of the second tree. It's guaranteed that the given points are distinct.

Output

If there is no solution to the problem, print -1. Otherwise print four space-separated integers x3, y3, x4, y4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them.

Note that x3, y3, x4, y4 must be in the range ( - 1000 ≤ x3, y3, x4, y4 ≤ 1000).

Examples

Input

0 0 0 1

Output

1 0 1 1

Input

0 0 1 1

Output

0 1 1 0

Input

0 0 1 2

Output

-1

```python
#!/usr/bin/env python3
import atexit
import io
import sys
import bisect

_I_B = sys.stdin.read().splitlines()
input = iter(_I_B).__next__
_O_B = io.StringIO()
sys.stdout = _O_B

@atexit.register
def write():
    sys.__stdout__.write(_O_B.getvalue())

def main():
    x1,y1,x2,y2=map(int,input().split())
    if x1==x2:
        d=abs(y1-y2)
        print(x1+d,y1,x2+d,y2)
    elif y1==y2:
        d=abs(x1-x2)
        print(x1,y1+d,x2,y2+d)
    elif abs(x1-x2)==abs(y1-y2):
        d=abs(x1-x2)
        if x2<x1:
            x1,x2=x2,x1
            y1,y2=y2,y1
        if y1>y2:
            print(x1,y1-d,x2,y2+d)
        else:
            print(x1,y1+d,x2,y2-d)

    else:
        print(-1)

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


47_E. Cannon

Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the Ox axis is directed rightwards in the city's direction, the Oy axis is directed upwards (to the sky). The cannon will make n more shots. The cannon balls' initial speeds are the same in all the shots and are equal to V, so that every shot is characterized by only one number alphai which represents the angle at which the cannon fires. Due to the cannon's technical peculiarities this angle does not exceed 45 angles (π / 4). We disregard the cannon sizes and consider the firing made from the point (0, 0).

The balls fly according to the known physical laws of a body thrown towards the horizon at an angle:

vx(t) = V·cos(alpha) vy(t) = V·sin(alpha) – g·t x(t) = V·cos(alpha)·t y(t) = V·sin(alpha)·t – g·t2 / 2

Think of the acceleration of gravity g as equal to 9.8.

Bertown defends m walls. The i-th wall is represented as a vertical segment (xi, 0) - (xi, yi). When a ball hits a wall, it gets stuck in it and doesn't fly on. If a ball doesn't hit any wall it falls on the ground (y = 0) and stops. If the ball exactly hits the point (xi, yi), it is considered stuck.

Your task is to find for each ball the coordinates of the point where it will be located in the end.

Input

The first line contains integers n and V (1 ≤ n ≤ 104, 1 ≤ V ≤ 1000) which represent the number of shots and the initial speed of every ball. The second line contains n space-separated real numbers alphai (0 < alphai < π / 4) which represent the angles in radians at which the cannon will fire. The third line contains integer m (1 ≤ m ≤ 105) which represents the number of walls. Then follow m lines, each containing two real numbers xi and yi (1 ≤ xi ≤ 1000, 0 ≤ yi ≤ 1000) which represent the wall’s coordinates. All the real numbers have no more than 4 decimal digits. The walls may partially overlap or even coincide.

Output

Print n lines containing two real numbers each — calculate for every ball the coordinates of its landing point. Your answer should have the relative or absolute error less than 10 - 4.

Examples

Input

2 10
0.7853
0.3
3
5.0 5.0
4.0 2.4
6.0 1.9

Output

5.000000000 2.549499369
4.000000000 0.378324889

Input

2 10
0.7853
0.3
2
4.0 2.4
6.0 1.9

Output

10.204081436 0.000000000
4.000000000 0.378324889

```python
import sys
from array import array  # noqa: F401
from math import pi, sin, cos
from bisect import bisect_left

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

n, v = map(int, input().split())
v = float(v)
alpha = [float(input()) for _ in range(n)]
m = int(input())
wall = sorted(tuple(map(float, input().split())) for _ in range(m)) + [(1e9, 1e9)]
max_angle = pi / 4
eps = 1e-9
a = [0.0] * m + [max_angle + eps]

for i in range(m):
    ng_angle, ok_angle = 0.0, max_angle + eps

    for _ in range(50):
        mid_angle = (ok_angle + ng_angle) / 2
        t = wall[i][0] / (v * cos(mid_angle))
        if (v * sin(mid_angle) * t - 9.8 * t**2 / 2) - eps <= wall[i][1]:
            ng_angle = mid_angle
        else:
            ok_angle = mid_angle

    a[i] = max(a[i], ng_angle)
    a[i + 1] = max(a[i], a[i + 1])

ans = [''] * n
for i in range(n):
    wi = bisect_left(a, alpha[i])

    ok, ng = 0.0, 1e7
    sin_a = sin(alpha[i])

    for _ in range(50):
        t = (ok + ng) / 2
        if v * sin_a * t - 9.8 * t**2 / 2 >= 0.0:
            ok = t
        else:
            ng = t

    x = v * cos(alpha[i]) * ok

    if x < wall[wi][0]:
        ans[i] = f'{x:.8f} {0:.8f}'
    else:
        ok, ng = 0.0, 1e7
        cos_a = cos(alpha[i])

        for _ in range(50):
            t = (ok + ng) / 2
            if v * cos_a * t <= wall[wi][0]:
                ok = t
            else:
                ng = t
        y = v * sin_a * ok - 9.8 * ok**2 / 2
        ans[i] = f'{wall[wi][0]:.8f} {y:.8f}'

print('\n'.join(ans))

```


554_A. Kyoya and Photobooks

Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?

Please help Haruhi solve this problem.

Input

The first line of input will be a single string s (1 ≤ |s| ≤ 20). String s consists only of lowercase English letters.

Output

Output a single integer equal to the number of distinct photobooks Kyoya Ootori can make.

Examples

Input

a

Output

51

Input

hi

Output

76

Note

In the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets.

```python
s = input()
l = list(s)
a = 'abcdefghijklmnopqrstuvwxyz'
for i in range(len(s)+1):
	for j in a:
		l.insert(i, j)
print(len(l)-2*len(s))
```


624_B. Making a String

You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:

  * the i-th letter occurs in the string no more than ai times;
  * the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.

Input

The first line of the input contains a single integer n (2 ≤ n ≤ 26) — the number of letters in the alphabet.

The next line contains n integers ai (1 ≤ ai ≤ 109) — i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.

Output

Print a single integer — the maximum length of the string that meets all the requirements.

Examples

Input

3
2 5 5

Output

11

Input

3
1 1 2

Output

3

Note

For convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".

```python
n = int(input())
m = list(map(int, input().split()))
m.sort(reverse = True)
ans = m[0]
last = m[0]
for i in range(1, len(m)):
    last = max(min(last - 1, m[i]), 0)
    ans += last
print(ans)
```


672_D. Robin Hood

We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.

There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people.

After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.

Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.

Input

The first line of the input contains two integers n and k (1 ≤ n ≤ 500 000, 0 ≤ k ≤ 109) — the number of citizens in Kekoland and the number of days left till Robin Hood's retirement.

The second line contains n integers, the i-th of them is ci (1 ≤ ci ≤ 109) — initial wealth of the i-th person.

Output

Print a single line containing the difference between richest and poorest peoples wealth.

Examples

Input

4 1
1 1 4 2

Output

2

Input

3 1
2 2 2

Output

0

Note

Lets look at how wealth changes through day in the first sample.

  1. [1, 1, 4, 2]
  2. [2, 1, 3, 2] or [1, 2, 3, 2]

So the answer is 3 - 1 = 2

In second sample wealth will remain the same for each person.

```python
import sys
sys.stderr = sys.stdout

def hood(n, k, C):
    C.sort()
    m, r = divmod(sum(C), n)
    m1 = (m + 1) if r else m

    c_lo = C[0]
    k_lo = k
    for i, c in enumerate(C):
        if c_lo == m:
            break
        c_m = min(c, m)
        dc = c_m - c_lo
        dk = i * dc
        if k_lo >= dk:
            k_lo -= dk
            c_lo = c_m
        else:
            dc = k_lo // i
            c_lo += dc
            break

    c_hi = C[-1]
    k_hi = k
    for i, c in enumerate(reversed(C)):
        if c_hi == m1:
            break
        c_m1 = max(c, m1)
        dc = c_hi - c_m1
        dk = i * dc
        if k_hi >= dk:
            k_hi -= dk
            c_hi = c_m1
        else:
            dc = k_hi // i
            c_hi -= dc
            break

    return c_hi - c_lo

def main():
    n, k = readinti()
    C = readintl()
    print(hood(n, k, C))

##########

def readint():
    return int(input())

def readinti():
   return map(int, input().split())

def readintt():
   return tuple(readinti())

def readintl():
   return list(readinti())

def readinttl(k):
    return [readintt() for _ in range(k)]

def readintll(k):
    return [readintl() for _ in range(k)]

def log(*args, **kwargs):
    print(*args, **kwargs, file=sys.__stderr__)

if __name__ == '__main__':
    main()

```


763_B. Timofey and rectangles

One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.

Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.

Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length

<image> The picture corresponds to the first example

Input

The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles.

n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109,  - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle.

It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other.

Output

Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color.

Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle.

Example

Input

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

Output

YES
1
2
2
3
2
2
4
1

```python
n = int(input())
coordinates = []
for i in range(n):
    coordinates.append([int(x) % 2 for x in input().split()])
print('YES')
for coordinate in coordinates:
    x1, y1, x2, y2 = coordinate
    print(2*x2 + y2 + 1)

```


808_C. Tea Party

Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1, a2, ..., an. His teapot stores w milliliters of tea (w ≤ a1 + a2 + ... + an). Polycarp wants to pour tea in cups in such a way that:

  * Every cup will contain tea for at least half of its volume
  * Every cup will contain integer number of milliliters of tea
  * All the tea from the teapot will be poured into cups
  * All friends will be satisfied.

Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but ai > aj.

For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.

Input

The first line contains two integer numbers n and w (1 ≤ n ≤ 100, <image>).

The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 100).

Output

Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.

If it's impossible to pour all the tea and satisfy all conditions then output -1.

Examples

Input

2 10
8 7

Output

6 4

Input

4 4
1 1 1 1

Output

1 1 1 1

Input

3 10
9 8 10

Output

-1

Note

In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.

```python
import math
import re

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

a1 = [math.ceil(el/2) for el in a]

s = w - sum(a1)

if s < 0:
    print(-1)
elif s == 0:
    print(' '.join(map(str, a1)))
else:
    for i in range(n):
        if a[i] == 1:
            a1[i] = 0
            a[i] = 0

    a2 = sorted(a, reverse=True)
    #print(a)

    while s > 0:

        i = a.index(a2[0])

        #print(a1)
        #print(i)
        if a[i] - a1[i] < s:
            s -= (a[i] - a1[i])
            a1[i] = a[i]
        else:
            a1[i] += s
            s = 0
        del (a2[0])

        a[i] = -1
    for i in range(n):
        if a1[i] == 0:
            a1[i] = 1

    print(' '.join(map(str, a1)))

# n, m = map(int, input().split())
# w = []
# c = []
# for i in range(n):
#     x, y = map(int, input().split())
#     w.append(x)
#     c.append(y)
#
# A = [[0] * (m + 1) for i in range(n)]
#
#
# for k in range(n):
#       for s in range(1, m + 1):
#             if s >= w[k]:
#                 A[k][s] = max(A[k - 1][s], A[k - 1][s - w[k]] + c[k])
#             else:
#                 A[k][s] = A[k-1][s]
#
# print(A[n - 1][m])

    # arr = list(map(int, input().split()))
# res = 0
# a = {math.pow(2, i) for i in range(35)}
# for i in range(n-1):
#     for j in range(i+1,n):
#         if arr[i] + arr[j] % 2 % 2 % 2 % 2 % 2 in a:
#             res += 1
#
# print(res)

# arr = list(map(int, input().split()))
# m = int(input())
# spis = list(map(int, input().split()))
#
# arr1 = sorted(arr, reverse=True)
# a = [n - arr1.index(arr[el - 1]) for el in spis]
# print(' '.join(map(str, a)))
```


832_D. Misha, Grisha and Underground

Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.

The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean.

The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.

Input

The first line contains two integers n and q (2 ≤ n ≤ 105, 1 ≤ q ≤ 105) — the number of stations and the number of days.

The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.

The next q lines contains three integers a, b and c each (1 ≤ a, b, c ≤ n) — the ids of stations chosen by boys for some day. Note that some of these ids could be same.

Output

Print q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.

Examples

Input

3 2
1 1
1 2 3
2 3 3

Output

2
3

Input

4 1
1 2 3
1 2 3

Output

2

Note

In the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 <image> 2, and Grisha would go on the route 3 <image> 1 <image> 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 <image> 1 <image> 2. Grisha would see the text at 3 stations.

In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 <image> 2 <image> 3, and Grisha would go on the route 2 <image> 3 and would see the text at both stations.

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

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

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

MA=10**5+1
level=20
tree=[[] for i in range(MA)]
depth=[0 for i in range(MA)]
parent=[[0 for i in range(level)] for j in range(MA)]

@bootstrap
def dfs(cur,prev):
    depth[cur] = depth[prev] + 1
    parent[cur][0] = prev
    for i in range(len(tree[cur])):
        if (tree[cur][i] != prev):
            yield dfs(tree[cur][i], cur)

    yield

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

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

    diff = depth[v] - depth[u]

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

    if (u == v):
        return u

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

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

        i+=-1

    return parent[u][0]

def add(a,b):
    tree[a].append(b)
    tree[b].append(a)

def res(s,t,f):
    p=lca(t,f)
    q=lca(s,f)
    if p==q:
        r=depth[lca(s,t)]-depth[p]
        return min(depth[p] + depth[f] - 2 * depth[p] + 1+r, depth[q] + depth[f] - 2 * depth[q] + 1+r)

    return min(depth[p]+depth[f]-2*depth[p]+1,depth[q]+depth[f]-2*depth[q]+1)

n,q=map(int,input().split())
p=list(map(int,input().split()))

for j in range(n-1):
    tree[p[j]].append(j+2)
    tree[j+2].append(p[j])

dfs(1,0)
precomputeSparseMatrix(n)
for j in range(q):
    a,b,c=map(int,input().split())
    print(max(res(a,b,c),res(a,c,b),res(b,c,a)))

```


853_B. Jury Meeting

Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.

There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.

You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.

Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.

Input

The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).

The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.

Output

Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities.

If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).

Examples

Input

2 6 5
1 1 0 5000
3 2 0 5500
2 2 0 6000
15 0 2 9000
9 0 1 7000
8 0 2 6500

Output

24500

Input

2 4 5
1 2 0 5000
2 1 0 4500
2 1 0 3000
8 0 1 6000

Output

-1

Note

The optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.

In the second sample it is impossible to send jury member from city 2 back home from Metropolis.

```python
from bisect import *
from sys import *
n,m,k=[int(i) for i in input().split()]
pln=[]
if m==0:
    print(-1)
    exit(0)
for i in range(m):
    pln.append([int(i) for i in input().split()])
pln.sort()

grp=[[pln[0]]];gt=0;
for i in range(1,m):
    if pln[i][0]!=pln[i-1][0]:
        gt=gt+1
        grp.append([])
    grp[gt].append(pln[i])
xx=[]
for i in range(len(grp)):
    xx.append(grp[i][0][0])
#print('grp',grp)
#print('xx',xx)

from math import inf
pre=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
for i,x in enumerate(grp):
    for di,fi,ti,ci in x:
        if ti==0:
            if mincost[fi]==inf:
                ct+=1
            if sumcost==inf:
                mincost[fi]=min(mincost[fi],ci)
            else:
                sumcost=sumcost-mincost[fi]
                mincost[fi]=min(mincost[fi],ci)
                sumcost=sumcost+mincost[fi]
    if ct==n and sumcost==inf:
        sumcost=sum(mincost[1:])
    pre[i]=sumcost
#print(pre)

sa=[0]*len(xx)
ct=0
mincost=[inf]*(n+1);sumcost=inf
grp.reverse()
for i,x in enumerate(grp):
    for di,fi,ti,ci in x:
        if fi==0:
            if mincost[ti]==inf:
                ct+=1
            if sumcost==inf:
                mincost[ti]=min(mincost[ti],ci)
            else:
                sumcost=sumcost-mincost[ti]
                mincost[ti]=min(mincost[ti],ci)
                sumcost=sumcost+mincost[ti]
    if ct==n and sumcost==inf:
        sumcost=sum(mincost[1:])
    sa[i]=sumcost
sa.reverse()
#print(sa)

ans=inf
for l,xxi in enumerate(xx):
    r=bisect_right(xx,xxi+k)
    ansl=pre[l]
    ansr= inf if r==len(xx) else sa[r]
    ans=min(ans,ansl+ansr)
print(ans) if ans!=inf else print(-1)

```


877_F. Ann and Books

In Ann's favorite book shop are as many as n books on math and economics. Books are numbered from 1 to n. Each of them contains non-negative number of problems.

Today there is a sale: any subsegment of a segment from l to r can be bought at a fixed price.

Ann decided that she wants to buy such non-empty subsegment that the sale operates on it and the number of math problems is greater than the number of economics problems exactly by k. Note that k may be positive, negative or zero.

Unfortunately, Ann is not sure on which segment the sale operates, but she has q assumptions. For each of them she wants to know the number of options to buy a subsegment satisfying the condition (because the time she spends on choosing depends on that).

Currently Ann is too busy solving other problems, she asks you for help. For each her assumption determine the number of subsegments of the given segment such that the number of math problems is greaten than the number of economics problems on that subsegment exactly by k.

Input

The first line contains two integers n and k (1 ≤ n ≤ 100 000,  - 109 ≤ k ≤ 109) — the number of books and the needed difference between the number of math problems and the number of economics problems.

The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 2), where ti is 1 if the i-th book is on math or 2 if the i-th is on economics.

The third line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109), where ai is the number of problems in the i-th book.

The fourth line contains a single integer q (1 ≤ q ≤ 100 000) — the number of assumptions.

Each of the next q lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n) describing the i-th Ann's assumption.

Output

Print q lines, in the i-th of them print the number of subsegments for the i-th Ann's assumption.

Examples

Input

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

Output

2
3
4
1

Input

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

Output

10

Note

In the first sample Ann can buy subsegments [1;1], [2;2], [3;3], [2;4] if they fall into the sales segment, because the number of math problems is greater by 1 on them that the number of economics problems. So we should count for each assumption the number of these subsegments that are subsegments of the given segment.

Segments [1;1] and [2;2] are subsegments of [1;2].

Segments [1;1], [2;2] and [3;3] are subsegments of [1;3].

Segments [1;1], [2;2], [3;3], [2;4] are subsegments of [1;4].

Segment [3;3] is subsegment of [3;4].

```python
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

# ------------------- fast io --------------------
from math import ceil

def prod(a, mod=10 ** 9 + 7):
    ans = 1
    for each in a:
        ans = (ans * each) % mod
    return ans

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

def lcm(a, b): return a * b // gcd(a, b)

def binary(x, length=16):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y

for _ in range(int(input()) if not True else 1):
    #n = int(input())
    n, k = map(int, input().split())
    # a, b = map(int, input().split())
    # c, d = map(int, input().split())
    t = list(map(int, input().split()))
    a = list(map(int, input().split()))
    # s = input()
    for i in range(n):
        # math = eco + k
        # math - eco = k
        if t[i] == 2:
            a[i] *= -1

    count = [0] * (n + 1)
    pre = [0]
    for i in a:
        pre += [pre[-1] + i]

    index = {}
    cc = list(set(pre))
    for i in range(len(cc)):
        index[cc[i]] = i

    minusK = [-1]*(n + 1)
    plusK = [-1] * (n + 1)
    zero = [-1] * (n + 1)
    for i in range(n + 1):
        if pre[i] - k in index:
            minusK[i] = index[pre[i] - k]
        if pre[i] + k in index:
            plusK[i] = index[pre[i] + k]
        zero[i] = index[pre[i]]

    BLOCK_SIZE = 320
    blocks = [[] for i in range(BLOCK_SIZE)]
    q = int(input())
    ans = [0]*q
    for i in range(q):
        l, r = map(int, input().split())
        blocks[l // BLOCK_SIZE] += [[l-1, r, i]]

    for i in range(len(blocks)):
        if not blocks[i]: continue
        blocks[i] = sorted(blocks[i], key=lambda x: x[1])
        left = right = BLOCK_SIZE * i
        res = 0
        count[zero[left]] += 1
        for l, r, ind in blocks[i]:
            while right < r:
                right += 1
                if minusK[right] != -1:
                    res += count[minusK[right]]
                count[zero[right]] += 1
            while left < l:
                count[zero[left]] -= 1
                if plusK[left] != -1:
                    res -= count[plusK[left]]
                left += 1
            while left > l:
                left -= 1
                if plusK[left] != -1:
                    res += count[plusK[left]]
                count[zero[left]] += 1
            ans[ind] = res

        while left <= right:
            count[zero[left]] -= 1
            if plusK[left] != -1:
                res -= count[plusK[left]]
            left += 1
        assert res == 0

    for i in ans:
        print(i)
```


901_B. GCD of Polynomials

Suppose you have two polynomials <image> and <image>. Then polynomial <image> can be uniquely represented in the following way:

<image>

This can be done using [long division](https://en.wikipedia.org/wiki/Polynomial_long_division). Here, <image> denotes the degree of polynomial P(x). <image> is called the remainder of division of polynomial <image> by polynomial <image>, it is also denoted as <image>.

Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials <image>. If the polynomial <image> is zero, the result is <image>, otherwise the result is the value the algorithm returns for pair <image>. On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question.

You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair <image> to pair <image>.

Input

You are given a single integer n (1 ≤ n ≤ 150) — the number of steps of the algorithm you need to reach.

Output

Print two polynomials in the following format.

In the first line print a single integer m (0 ≤ m ≤ n) — the degree of the polynomial.

In the second line print m + 1 integers between  - 1 and 1 — the coefficients of the polynomial, from constant to leading.

The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly n steps when called using these polynomials.

If there is no answer for the given n, print -1.

If there are multiple answer, print any of them.

Examples

Input

1

Output

1
0 1
0
1

Input

2

Output

2
-1 0 1
1
0 1

Note

In the second example you can print polynomials x2 - 1 and x. The sequence of transitions is

(x2 - 1, x) → (x, - 1) → ( - 1, 0).

There are two steps in it.

```python
"""
NTC here
"""
import sys
inp= sys.stdin.readline
input = lambda : inp().strip()
flush= sys.stdout.flush
# import threading
# sys.setrecursionlimit(10**6)
# threading.stack_size(2**25)

def iin(): return int(input())
def lin(): return list(map(int, input().split()))

# range = xrange
# input = raw_input

def main():
    n = iin()
    ans  = [0]*(n+1)
    ans[0]=1
    ans1 = [0]*(n+1)
    sol = 0
    # print(ans, ans1)
    for i in range(n):
        su = ans1[:]
        for j in range(n):
            su[j+1]+=ans[j]
            if su[j+1]>1:su[j+1]=0
        # print(1, su, ans)
        ans, ans1= su, ans
        # print(ans, ans1, mx)
    if sol:
        print(-1)
    else:
        m1, m2=0, 0
        for i in range(n+1):
            if abs(ans[i]):
                m1 = i+1
            if abs(ans1[i]):
                m2 = i+1
        print(m1-1)
        print( *ans[:m1])
        print( m2-1)
        print( *ans1[:m2])

main()
# threading.Thread(target=main).start()

```


952_A. Quirky Quantifiers

Input

The input contains a single integer a (10 ≤ a ≤ 999).

Output

Output 0 or 1.

Examples

Input

13

Output

1

Input

927

Output

1

Input

48

Output

0

```python
b=int(input())
if b%2==0:
    print(0)
else:
    print(1)
```


979_C. Kuro and Walking Route

Kuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u ≠ v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).

Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.

Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.

Input

The first line contains three integers n, x and y (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ x, y ≤ n, x ≠ y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.

n - 1 lines follow, each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), describes a road connecting two towns a and b.

It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.

Output

A single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.

Examples

Input

3 1 3
1 2
2 3

Output

5

Input

3 1 3
1 2
1 3

Output

4

Note

On the first example, Kuro can choose these pairs:

  * (1, 2): his route would be 1 → 2,
  * (2, 3): his route would be 2 → 3,
  * (3, 2): his route would be 3 → 2,
  * (2, 1): his route would be 2 → 1,
  * (3, 1): his route would be 3 → 2 → 1.

Kuro can't choose pair (1, 3) since his walking route would be 1 → 2 → 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).

On the second example, Kuro can choose the following pairs:

  * (1, 2): his route would be 1 → 2,
  * (2, 1): his route would be 2 → 1,
  * (3, 2): his route would be 3 → 1 → 2,
  * (3, 1): his route would be 3 → 1.

```python

def calculate_max_paths(edges, node, dest,  par, cnt):
    ans = 1
    for child in edges.get(node, []):
        if child != par:
            ans += calculate_max_paths(edges, child, dest, node,  cnt)
    if dest == node:
        cnt[0] = ans
    return ans

def main():
    from collections import defaultdict
    n, flower, bee = list(map(int, input().split()))
    edges = defaultdict(list)
    for _ in range(n-1):
        x, y = list(map(int, input().split()))
        edges[x].append(y)
        edges[y].append(x)
    bees, flowers = [0], [0]
    x = calculate_max_paths(edges, flower, bee,  par=None, cnt=bees)
    y = calculate_max_paths(edges, bee, flower, par=None, cnt=flowers)
    print(x*(x-1) - bees[0]*flowers[0])

if __name__=="__main__":
    import sys
    import threading
    sys.setrecursionlimit(10**6)
    threading.stack_size(10**8)
    t = threading.Thread(target=main)
    t.start()
    t.join()
```


999_D. Equalize the Remainders

You are given an array consisting of n integers a_1, a_2, ..., a_n, and a positive integer m. It is guaranteed that m is a divisor of n.

In a single move, you can choose any position i between 1 and n and increase a_i by 1.

Let's calculate c_r (0 ≤ r ≤ m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder.

Your task is to change the array in such a way that c_0 = c_1 = ... = c_{m-1} = n/m.

Find the minimum number of moves to satisfy the above requirement.

Input

The first line of input contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ n). It is guaranteed that m is a divisor of n.

The second line of input contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), the elements of the array.

Output

In the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals n/m.

In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}.

Examples

Input

6 3
3 2 0 6 10 12

Output

3
3 2 0 7 10 14

Input

4 2
0 1 2 3

Output

0
0 1 2 3

```python
from collections import deque
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
a = list(map(int, input().split()))
cnt = [0] * m
x = [[] for _ in range(m)]
for i in range(n):
    ai = a[i] % m
    cnt[ai] += 1
    x[ai].append(i)
l = n // m
q = deque()
for i in range(m):
    if cnt[i] < l:
        q.append(i)
ans = 0
for i in range(m):
    for j in x[i]:
        if cnt[i] <= l:
            break
        while q[0] < i:
            q.append(q.popleft() + m)
        k = q[0] % m
        cnt[k] += 1
        cnt[i] -= 1
        ans += (k - i) % m
        a[j] += (k - i) % m
        if cnt[k] == l:
            q.popleft()
print(ans)
print(*a)
```


p02534 ACL Beginner Contest - Repeat ACL

You are given an integer K. Print the string obtained by repeating the string `ACL` K times and concatenating them.

For example, if K = 3, print `ACLACLACL`.

Constraints

* 1 \leq K \leq 5
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the string obtained by repeating the string `ACL` K times and concatenating them.

Example

Input

3

Output

ACLACLACL

```python
K=int(input())
print("ACL"*K)
```


p02666 NOMURA Programming Competition 2020 - Urban Planning

There are N towns numbered 1, 2, \cdots, N.

Some roads are planned to be built so that each of them connects two distinct towns bidirectionally. Currently, there are no roads connecting towns.

In the planning of construction, each town chooses one town different from itself and requests the following: roads are built so that the chosen town is reachable from itself using one or more roads.

These requests from the towns are represented by an array P_1, P_2, \cdots, P_N. If P_i = -1, it means that Town i has not chosen the request; if 1 \leq P_i \leq N, it means that Town i has chosen Town P_i.

Let K be the number of towns i such that P_i = -1. There are (N-1)^K ways in which the towns can make the requests. For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).

Constraints

* 2 \leq N \leq 5000
* P_i = -1 or 1 \leq P_i \leq N.
* P_i \neq i
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \cdots P_N

Output

For each way to make requests, find the minimum number of roads needed to meet all the requests, and print the sum of those (N-1)^K numbers, modulo (10^9+7).

Examples

Input

4
2 1 -1 3

Output

8

Input

2
2 1

Output

1

Input

10
2 6 9 -1 6 9 -1 -1 -1 -1

Output

527841

```python
def modfac(n, MOD):

    f = 1
    factorials = [1]
    for m in range(1, n + 1):
        f *= m
        f %= MOD
        factorials.append(f)
    inv = pow(f, MOD - 2, MOD)
    invs = [1] * (n + 1)
    invs[n] = inv
    for m in range(n, 1, -1):
        inv *= m
        inv %= MOD
        invs[m - 1] = inv
    return factorials, invs

def modnCr(n,r,mod,fac,inv): #上で求めたfacとinvsを引数に入れるべし(上の関数で与えたnが計算できる最大のnになる)

    return fac[n] * inv[n-r] * inv[r] % mod

def uf_find(n,p):

    ufl = []

    while p[n] != n:
        ufl.append(n)
        n = p[n]

    for i in ufl:
        p[i] = n

    return n

def uf_union(a,b,p,rank,tsize):

    ap = uf_find(a,p)
    bp = uf_find(b,p)

    if ap == bp:
        return True
    else:

        if rank[ap] > rank[bp]:
            p[bp] = ap
            tsize[ap] += tsize[bp]
        elif rank[ap] < rank[bp]:
            p[ap] = bp
            tsize[bp] += tsize[ap]
        else:
            p[bp] = ap
            rank[ap] += 1
            tsize[ap] += tsize[bp]

        return False

mod = 10**9+7
N = int(input())
P = list(map(int,input().split()))
fac,inv = modfac(N+10,mod)

ans = 0

p = [i for i in range(N)]
rank = [1] * N
tsize = [1] * N

for i in range(N):

    if P[i] == -1:
        continue
    nex = P[i] - 1
    uf_union(i,nex,p,rank,tsize)

able = [True] * N
c = []
d = []

for i in range(N):

    if P[i] == -1:
        nowp = uf_find(i,p)
        c.append(tsize[nowp])
        able[nowp] = False

for i in range(N):

    if uf_find(i,p) == i and able[i]:
        d.append(tsize[i])

ans = 0
for i in c:
    ans += i
for i in d:
    ans += i-1
ans *= pow(N-1,len(c),mod)
ans %= mod

#print (ans)

#自分を選んで減る場合
for i in c:
    ans -= (i-1) * pow(N-1,len(c)-1,mod)
    ans %= mod

#互いに選んで減る場合

dp = [0] * (len(c)+1)
dp[0] = 1

for i in c:
    for j in range(len(c)-1,-1,-1):
        dp[j+1] += dp[j] * i
        #dp[j+1] %= mod
#print (c,dp)

for i in range(2,len(c)+1):

    ans -= dp[i] * fac[i-1] * pow(N-1,len(c)-i,mod)
    ans %= mod

print (ans % mod)

"""
連結成分で考える
全ての街が -1 以外を選んだ時、
最小数 + -1の数
-1同士が選ぶことを考える
-1同士が選んだ時のみ答えが1減る
そうでなければ変化なし？

連結成分に-1は1つ以下しかない？
→正しい

-1を含まない連結成分は分けておく
-1の連結成分同士が求め合えば、答えは-1される

a個含む & bこ含む
場合

a*b * (N-1)^(K-2)
引けばいい

自分の連結成分を求めるときも1減る
ループを作ると1減るんだ！

"""

```


p02795 Keyence Programming Contest 2020 - Painting

We have a grid with H rows and W columns, where all the squares are initially white.

You will perform some number of painting operations on the grid. In one operation, you can do one of the following two actions:

* Choose one row, then paint all the squares in that row black.
* Choose one column, then paint all the squares in that column black.

At least how many operations do you need in order to have N or more black squares in the grid? It is guaranteed that, under the conditions in Constraints, having N or more black squares is always possible by performing some number of operations.

Constraints

* 1 \leq H \leq 100
* 1 \leq W \leq 100
* 1 \leq N \leq H \times W
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

H
W
N

Output

Print the minimum number of operations needed.

Examples

Input

3
7
10

Output

2

Input

14
12
112

Output

8

Input

2
100
200

Output

2

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

print(min([(n+h-1)//h, (n+w-1)//w]))
```


p02931 Japanese Student Championship 2019 Qualification - Card Collector

There are N cards placed on a grid with H rows and W columns of squares.

The i-th card has an integer A_i written on it, and it is placed on the square at the R_i-th row from the top and the C_i-th column from the left.

Multiple cards may be placed on the same square.

You will first pick up at most one card from each row.

Then, you will pick up at most one card from each column.

Find the maximum possible sum of the integers written on the picked cards.

Constraints

* All values are integers.
* 1 \leq N \leq 10^5
* 1 \leq H, W \leq 10^5
* 1 \leq A_i \leq 10^5
* 1 \leq R_i \leq H
* 1 \leq C_i \leq W

Input

Input is given from Standard Input in the following format:

N H W
R_1 C_1 A_1
R_2 C_2 A_2
\vdots
R_N C_N A_N

Output

Print the maximum possible sum of the integers written on the picked cards.

Examples

Input

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

Output

28

Input

13 5 6
1 3 35902
4 6 19698
4 6 73389
3 6 3031
3 1 4771
1 4 4784
2 1 36357
2 1 24830
5 6 50219
4 6 22645
1 2 30739
1 4 68417
1 5 78537

Output

430590

Input

1 100000 100000
1 1 1

Output

1

```python
import sys
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

N,H,W = map(int,readline().split())
RCA = [tuple(int(x) for x in line.split()) for line in readlines()]

RCA.sort(key = lambda x: -x[2])

RCA

root = list(range(H+W))
size = [0] * (H+W)
no_cycle = [True] * (H+W)

def find_root(x):
    y = root[x]
    if x == y:
        return y
    z = find_root(y)
    root[x] = z
    return z

def merge(x,y):
    x,y = find_root(x),find_root(y)
    sx,sy = size[x],size[y]
    if sx < sy:
        sx,sy = sy,sx
        x,y = y,x
    root[y] = x
    no_cycle[x] = no_cycle[x] and no_cycle[y]

answer = 0
for R,C,A in RCA:
    x,y = R-1,H+C-1
    rx,ry = find_root(x),find_root(y)
    if rx == ry:
        if not no_cycle[rx]:
            continue
        no_cycle[rx] = False
    else:
        if (not no_cycle[rx]) and (not no_cycle[ry]):
            continue
        merge(rx,ry)
    answer += A

print(answer)

```


p03067 Tenka1 Programmer Beginner Contest 2019 - On the Way

There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively. Print `Yes` if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print `No` otherwise.

Constraints

* 0\leq A,B,C\leq 100
* A, B and C are distinct integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print `Yes` if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print `No` otherwise.

Examples

Input

3 8 5

Output

Yes

Input

7 3 1

Output

No

Input

10 2 4

Output

Yes

Input

31 41 59

Output

No

```python
a, b, c = map(int, input().split())
if (c-a)*(c-b) < 0:
	print("Yes")
else:
	print("No")
```


p03210 AtCoder Beginner Contest 114 - 753

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

* 1 ≤ X ≤ 9
* X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print `YES`; if it will not, print `NO`.

Examples

Input

5

Output

YES

Input

6

Output

NO

```python
a=int(input())
print('YES' if a in [3,5,7] else 'NO')
```


p03359 AtCoder Beginner Contest 096 - Day of Takahashi

In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.
For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.

In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.
How many days from 2018-1-1 through 2018-a-b are Takahashi?

Constraints

* a is an integer between 1 and 12 (inclusive).
* b is an integer between 1 and 31 (inclusive).
* 2018-a-b is a valid date in Gregorian calendar.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.

Examples

Input

5 5

Output

5

Input

2 1

Output

1

Input

11 30

Output

11

```python
a, b = map(int, input().split())
print(a if (a <= b) else a - 1)

```


p03517 CODE FESTIVAL 2017 Elimination Tournament Round 2 (Parallel) - Colorful MST

Ringo has an undirected graph G with N vertices numbered 1,2,...,N and M edges numbered 1,2,...,M. Edge i connects Vertex a_{i} and b_{i} and has a length of w_i.

Now, he is in the middle of painting these N vertices in K colors numbered 1,2,...,K. Vertex i is already painted in Color c_i, except when c_i = 0, in which case Vertex i is not yet painted.

After he paints each vertex that is not yet painted in one of the K colors, he will give G to Snuke.

Based on G, Snuke will make another undirected graph G' with K vertices numbered 1,2,...,K and M edges. Initially, there is no edge in G'. The i-th edge will be added as follows:

* Let x and y be the colors of the two vertices connected by Edge i in G.
* Add an edge of length w_i connecting Vertex x and y in G'.

What is the minimum possible sum of the lengths of the edges in the minimum spanning tree of G'? If G' will not be connected regardless of how Ringo paints the vertices, print -1.

Constraints

* 1 \leq N,M \leq 10^{5}
* 1 \leq K \leq N
* 0 \leq c_i \leq K
* 1 \leq a_i,b_i \leq N
* 1 \leq w_i \leq 10^{9}
* The given graph may NOT be simple or connected.
* All input values are integers.

Input

Input is given from Standard Input in the following format:

N M K
c_1 c_2 ... c_{N}
a_1 b_1 w_1
:
a_M b_M w_M

Output

Print the answer.

Examples

Input

4 3 3
1 0 1 2
1 2 10
2 3 20
2 4 50

Output

60

Input

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

Output

-1

Input

9 12 9
1 2 3 4 5 6 7 8 9
6 9 9
8 9 6
6 7 85
9 5 545631016
2 1 321545
1 6 33562944
7 3 84946329
9 7 15926167
4 7 53386480
5 8 70476
4 6 4549
4 8 8

Output

118901402

Input

18 37 12
5 0 4 10 8 7 2 10 6 0 9 12 12 11 11 11 0 1
17 1 1
11 16 7575
11 15 9
10 10 289938980
5 10 17376
18 4 1866625
8 11 959154208
18 13 200
16 13 2
2 7 982223
12 12 9331
13 12 8861390
14 13 743
2 10 162440
2 4 981849
7 9 1
14 17 2800
2 7 7225452
3 7 85
5 17 4
2 13 1
10 3 45
1 15 973
14 7 56553306
16 17 70476
7 18 9
9 13 27911
18 14 7788322
11 11 8925
9 13 654295
2 10 9
10 1 545631016
3 4 5
17 12 1929
2 11 57
1 5 4
1 17 7807368

Output

171

```python
class Unionfindtree:
    def __init__(self, number):
        self.par = [i for i in range(number)]
        self.rank = [0] * (number)

    def find(self, x):  # 親を探す
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):  # x,yを繋げる
        px = self.find(x)
        py = self.find(y)
        if px == py:
            return
        if self.rank[px] < self.rank[py]:
            self.par[px] = py
        else:
            self.par[py] = px
        if self.rank[px] == self.rank[py]:
            self.rank[px] += 1

    def connect(self, x, y):  # 親が同じかみる
        return self.find(x) == self.find(y)

N, M, K = map(int, input().split())
C = [int(i) for i in input().split()]
table = []
t = K
for i in range(N):
    if C[i]==0:
        t+=1
        C[i]=t
for i in range(M):
    s, u, c = map(int, input().split())
    a, b = C[s - 1], C[u - 1]
    table.append((c, a, b))

tree = Unionfindtree(t+1)
table.sort()
ct = K - 1
ans = 0
for c, a, b in table:
    if not tree.connect(a, b) and ct > 0:
        tree.union(a, b)
        ans += c
        ct -= 1
if ct > 0:
    print(-1)
else:
    print(ans)

```


p03680 AtCoder Beginner Contest 065 - Trained?

Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.

The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up. These buttons are numbered 1 through N. When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It is possible that i=a_i. When Button i is not lighten up, nothing will happen by pressing it.

Initially, Button 1 is lighten up. Takahashi wants to quit pressing buttons when Button 2 is lighten up.

Determine whether this is possible. If the answer is positive, find the minimum number of times he needs to press buttons.

Constraints

* 2 ≤ N ≤ 10^5
* 1 ≤ a_i ≤ N

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

Print -1 if it is impossible to lighten up Button 2. Otherwise, print the minimum number of times we need to press buttons in order to lighten up Button 2.

Examples

Input

3
3
1
2

Output

2

Input

4
3
4
1
2

Output

-1

Input

5
3
3
4
2
4

Output

3

```python
n=int(input())
l=[int(input()) for i in range(n)]
a=1
ans=0
while a!=2:
    a=l[a-1]
    ans+=1
    if ans==n+1:
        ans=-1
        break
print(ans)

```